0
//java program that asks user to input a number and print the 1st and 2nd largest numbers

import java.util.Scanner;

public class twolargestnum
{
    public static void main(String args[])
    {
        Scanner input=new Scanner(System.in);

        int largest_2=0; //initializes second number
        int largest=0; //initializes first number
        int number;
        int counter=0;//initializes counter



        while(counter<10)
        {
            System.out.println("enter the number:");
            number=input.nextInt();//prompts user

            if(largest<number){
            largest=number;//stores number to largest
            largest_2=largest;}//stores largest to second largest or         largest_2
            else{

            if(largest_2<number &&largest>largest_2)
            largest_2=number; //stores second largest to number


            }
            counter=counter+1;//counts number input 10 times
    }

        System.out.println("The first largest number is "         +largest);//displays largest number inputed
    System.out.println("The second largest number is " +largest_2);//displays second largest number inputed

     }

}

Output

enter the number:
99
enter the number:
88
enter the number:
77
enter the number:
66
enter the number:
55
enter the number:
44
enter the number:
33
enter the number:
22
enter the number:
11
enter the number:
10
The first largest number is 99
The second largest number is 99 

As you can see , the program displays the second largest number as 99 instead of 88. what am I doing wrong?

3 Answers 3

1

At the very least swap these two lines:

        largest=number;//stores number to largest
        largest_2=largest;//stores largest to second largest or
Sign up to request clarification or add additional context in comments.

Comments

1

You need to change the largest_2 to largest BEFORE you update largest.

Comments

0

This is a classic mistake.

largest = number;
largest_2 = largest;

You are essentially changing (deleting) the stored value for largest when you perform the first operation. @Ishamael is correct in saying you need to switch these two statements. The logic is that you are changing largest to number (which deletes the old largest) and then trying to assign a new variable (largest_2) to a deleted value. Where you need to use largest_2 to hold the value of largest before changing it's value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.