the code below compiles perfectly for 5 integers entered by the user.
what i want to do is alter my code so that i can as the user how many numbers the user wants in the list. then the program will ask the user to enter that many integers and then the program will find the largest of those integers. can anyone help me alter the code below to fit these new standards?
{
int integer1 =
Integer.parseInt(JOptionPane.showInputDialog( "Enter an integer:" ));
int integer2 =
Integer.parseInt(JOptionPane.showInputDialog( "Enter an integer:" ));
int integer3 =
Integer.parseInt(JOptionPane.showInputDialog( "Enter an integer:" ));
int integer4 =
Integer.parseInt(JOptionPane.showInputDialog( "Enter an integer:" ));
int integer5 =
Integer.parseInt(JOptionPane.showInputDialog( "Enter an integer:" ));
if (integer1 > integer2 && integer1 > integer3 && integer1 > integer4 && integer1 > integer5)
JOptionPane.showMessageDialog(null, "The largest number is: " + integer1);
if (integer2 > integer1 && integer2 > integer3 && integer2 > integer4 && integer2 > integer5)
JOptionPane.showMessageDialog(null, "The largest number is: " + integer2);
if (integer3 > integer2 && integer3 > integer1 && integer3 > integer4 && integer3 > integer5)
JOptionPane.showMessageDialog(null, "The largest number is: " + integer3);
if (integer4 > integer1 && integer4 > integer3 && integer4 > integer2 && integer4 > integer5)
JOptionPane.showMessageDialog(null, "The largest number is: " + integer4);
if (integer5 > integer1 && integer5 > integer3 && integer5 > integer4 && integer5 > integer2)
JOptionPane.showMessageDialog(null, "The largest number is: " + integer5);
}
i first want to prompt the user with
how many integers do you want in your list?
then i want to say
enter an integer:
as many times as the user said he wanted.
The key here is to use
Collections.max.The natural ordering for
Integeris from least-to-greatest, i.e. ascending. This makes it perfect to use here.Alternatively, you could just build the
Listusing a loop instead. See below for code that prompts the user to input the number of integers to enter.