# Java program to input 10 numbers and return the largest and 2nd largest



## SpeedRacer5

Hi. Big problem with an assignment. For some reason, when I input 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9 into this program, it tells me my largest is 9 and second is 0. Any Java experts here that can tell me how to fix this to have 8 as the result of 2nd largest?

--------------CODE----------------

import javax.swing.JOptionPane;
public class a3c4e23
{
public static void main (String args[])
{
int counter = 0;
int number;
int largest = 0;
int second = 0;
while (counter<10)
{
counter++;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number >= largest)
largest=number;
else if (number < largest && second >= number)
second=number;
else
largest = largest;
second = second;
}

System.out.println("Largest number input: " + largest);
System.out.println("Second largest input: " + second); }}

--------------CODE---------------------------

Thanks a bunch,

SpeedRacer5


----------



## Chicon

Hi SpeedRacer,

Why these lines ?


> else
> largest = largest;
> second = second;


----------



## SpeedRacer5

I don't know. No clue how to make it spit out the 2nd largest numbers.

Final program for my assignment for school and it seems easier than the others, but no clue how to make it work.


----------



## Chicon

Try this :


> while (counter<10)
> {
> counter++;
> number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
> if (number >= largest) largest=number;
> else if (number >= second) second=number;
> }


----------



## SpeedRacer5

When I use that code and put in numbers 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, it returns Largest as 9 and Second largest as 0.

I have no clue as to why.


----------



## SpeedRacer5

I've also set it up like this:

import javax.swing.JOptionPane;
public class a3c4e23
{
 public static void main (String args[])
{
int counter = 0;
int number;
int largest = 0;
int second = 0;
while (counter<10)
{
counter++;
number = Integer.parseInt(JOptionPane.showInputDialog("Enter integer"));
if (number >= largest) 
largest=number;
else if (number >= second && number <= largest) 
second=number;
}

System.out.println("Largest number input: " + largest);
System.out.println("Second largest input: " + second); }}

Following the logic, I figured that if the number is bigger than second and smaller than the largest, it would set number as second. Guess not.


----------

