这是我尝试过的代码,我可以将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);
}
}发布于 2014-02-14 04:57:43
//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.");发布于 2014-02-14 04:55:43
您应该在假设之前检查用户是否插入了一个整数(scanner.nextInt();)。
发布于 2014-02-14 04:56:25
您使用的是scanner.nextInt();,因此输入的文本应该是int,如果您输入的是int,而不是其他,则会抛出exception
https://stackoverflow.com/questions/21765257
复制相似问题