Ok, I am new to Java and had an assignment to find the smallest number (age) of three given ages. I figured it out, but my code is quite cumbersome. For my personal knowledge, and better understanding of java, I would like to know how I can shorten/improve my code. Here's what I have:
import javax.swing.JOptionPane;
class Exercise67
{
public static void main (String[ ] args)
{ JOptionPane.showMessageDialog (null,
"Finding who is youngest out of three people.");
new YoungestOfThree();
System.exit (0);
} //======================
} //########################################################
public class YoungestOfThree extends Object
{
/** Find the youngest (lowest) age of three people. */
public YoungestOfThree()
{ String input = JOptionPane.showInputDialog
("Enter first age.");
String input2 = JOptionPane.showInputDialog
("Enter second age.");
String input3 = JOptionPane.showInputDialog
("Enter third age.");
int age1 = Integer.parseInt (input);
int age2 = Integer.parseInt (input2);
int age3 = Integer.parseInt (input3);
int counter = 1;
int smallest = age1;
while (counter < 4)
{ if (age1 > age2)
smallest = age2;
if (age2 > age3)
smallest = age3;
counter++;
}
JOptionPane.showMessageDialog
(null, "The youngest age is: " + smallest);
} //======================
}
As I said, it works just fine, but if I was going to find the lowest number of say, 100 numbers, this would be far too cumbersome to use. Thanks for your time.