这是我尝试过的代码,我可以将 5 个整数放入数组中,但我的问题是验证该输入并在未验证时给出错误消息。如果我输入 5 个整数并且它们在所需范围内,则它可以工作,当我输入不在所需范围内的数字时,我会收到一条错误消息,这正是我想要的,但如果我输入符号或字母我的程序崩溃。
import java.util.Scanner;
public class QuestionNr1 {
public static void main(String[] args) {
//Keyboard Initialization
Scanner scanner = new Scanner(System.in);
//Declare an array to hold 5 integers values
int list[] = new int[5];
int i = 0;
int sum = 0;
System.out.println("Please enter 5 numbers within the range 1 - 20, with 1 being the lowest and 20 being the highest.");
while (i < 5) {
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = scanner.nextInt();
if (value >= 0 && value <= 20) {
list[i] = value;
i++;
} else {
System.out.println("Invalid input, please enter a number with the required range of 1 - 20.");
}
}
for (int j = 0; j < list.length; j++) {
int value = list[j];
}
double average = 0;
for (int i1 = 0; i1 < list.length; i1++) {
sum = sum + list[i1];
}
System.out.print("The sum total of your five entered numbers = " + sum);
}
}
最佳答案
//Fill the array with integers from the keyboard (range: 0 to 20).
int value = Integer.MIN_VALUE;
if (scanner.hasNextInt()) int value = scanner.nextInt();
else System.out.println("Please make sure the value you entered is an integer.");
关于java - 我正在用java创建一个小程序,它要求用户输入5个整数并将其放入一个数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21765257/