该程序应该接受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);
}
}
}
答案 0 :(得分:0)
您需要移动显示JOptionPane
循环中输入的最大数字的while
语句
while (){
// code...
}
// Display the largest number
JOptionPane.showMessageDialog(null,
"The largest number entered is: " + largest, "Results",
JOptionPane.INFORMATION_MESSAGE);
答案 1 :(得分:0)
每次都不要评估你的输出。
//First get all ten numbers:
int[] numbers = new int[10]; //array of int to store 10 numbers
int counter=0;
while(counter<10){
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) {
numbers[counter]=number;
counter++;
}
// Display error message
else {
JOptionPane.showMessageDialog(null,
"Your entry was not a single digit, please re-enter.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
//Now After that loop evaluate your largers number
int max = 0;
while(counter <10)
{
if(numbers[counter] > max )
{
max == numbers
}
counter++;
}
// Display the largest number
JOptionPane.showMessageDialog(null,
"The largest number entered is: " + max , "Results",
JOptionPane.INFORMATION_MESSAGE);