|
printing two smallest numbers from a series of numbers
Instructions: Write and debug a program by implementing a class called twoSmallest, which prompts the user to enter a series of numbers. Each number can have a fractional part. The user indicates the end of the list by typing a “z” as the next number. The program then prints out the two smallest numbers among the list that the user typed. The result for this problem should be a Java file called twoSmallest.java.
I am having no problem exiting the loop and printing the smallest number, I just cant figure out how to print the second smallest number.
Any suggestions?
import java.util.Scanner; // Needed for the Scanner class
public class TwoSmallest
{
public static void main(String[] args)
{
double smallest = Double.MAX_VALUE;
double secondsmallest ;
// Create a Scanner object for keyboard input.
Scanner sc = new Scanner(System.in);
// Display general instructions.
System.out.println("Enter a series of numbers.");
System.out.println("Press Z to exit the program.\n");
boolean exit = false;
while (!exit)
{
System.out.print("Enter a value ");
String input = sc.next();
if (input.equalsIgnoreCase("Z"))
exit = true;
else
{
double x = Double.parseDouble(input);
smallest = Math.min(smallest ,x);
}
}
System.out.println("Smallest number: " + smallest);
}
}
|