Wednesday, 11 September 2013

Panel incorrectly showing repeatedly

Panel incorrectly showing repeatedly

This program is supposed to accept 10 single digit numbers and then output
the largest number entered. The program runs fine with the exception that
I get the output screen after each number entered. The output is correct.
I cannot figure out how to get the output screen to display only after all
10 have been entered.
package largest;
import javax.swing.*;
public class Largest {
// Main method
public static void main(String[] args) {
// Declare variables
int largest = 0;
int counter = 0;
int number = 0;
// Condition statement to repeat loop until 10 digits are entered
while (counter < 10) {
// Prompt user for input
String input = JOptionPane.showInputDialog(null,
"Enter a number between 0 and 9: ");
// Try-Catch statements to check and handle format errors
try {
number = Integer.parseInt(input);
} catch (NumberFormatException e) {
number = -1; // Triggers the error message
}
// Checks to make sure number is a single digit
if (number >= 0 && number < 10) {
// Determines if the number entered is the largest
if (number > largest) {
largest = number;
}
// Increases counter variable by 1 with a valid entry
counter++;
}
// Display error message
else {
JOptionPane.showMessageDialog(null,
"Your entry was not a single digit, please re-enter.",
"Error", JOptionPane.ERROR_MESSAGE);
}
// Display the largest number
JOptionPane.showMessageDialog(null,
"The largest number entered is: " + largest, "Results",
JOptionPane.INFORMATION_MESSAGE);
}
}
}

No comments:

Post a Comment