这个程序应该接受 10 个个位数的数字,然后输出输入的最大数字。该程序运行良好,除了在输入每个数字后我得到输出屏幕。输出是正确的。我无法弄清楚如何在输入全部 10 个之后才显示输出屏幕。
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);
}
}
}