我对Java编程还不够熟练,现在想写一个小程序,让用户输入3个1到10之间的整数,将它们保存在一个数组中,然后把这些整数加起来并告诉用户结果。目前为止,我已经写好了下面这段代码,并且它可以正常运行:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter 3 numbers in the range 1 to 10: ");
for (int i = 0; i < numArr.length; i++) {
numArr[i] = keyboard.nextInt();
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
我的问题是,我还需要验证输入的内容,例如,如果他们输入一个双精度数、一个字符串或者在1-10范围之外的数字。我尝试使用while循环,但我无法让程序正常工作,以下是我目前的代码。如果我去掉第一个while循环,第二个就能正常工作,也就是检查它是否为整数:
import java.util.Scanner;
public class Feb11a {
public static void main(String[] args) {
int[] numArr = new int[3];
int sum = 0;
Scanner keyboard = new Scanner(System.in);
for (int i = 0; i < numArr.length; i++) {
//check if between 1 and 10
while (i > 10 || i < 1) {
System.out.println("Enter a number in the range 1 to 10: ");
//check if integer
while (!keyboard.hasNextInt()) {
System.out.println("Invalid entry, please try again ");
keyboard.next();
}
numArr[i] = keyboard.nextInt();
}
}
for (int counter = 0; counter < numArr.length; counter++) {
sum += numArr[counter];
}
System.out.println("The sum of these numbers is " + sum);
}
}
我的问题是如何检查它是否是整数,且在1-10的范围内?