我正在尝试计算N个非负整数的平均值 . 我要求用户输入他们想要计算平均数的数量 . 然后让他们逐个输入数字 . 我也在使用try并在do语句中捕获,所以我可以再次提示用户,以防他们输入错误的值 .
如果任何输入的N个数字不是数字(int),我该如何重新提示用户 . 我重新提示用户重新启动 . 我很欣赏一些方向!
编辑:我使用相同的do while循环来捕获输入是否为非数字 . 我现在得到的是无数打印错误,并提示用户输入 . 我必须停止程序运行 .
编辑:问题是由于扫描仪没有被清除 . 通过在嵌套的do-while循环中添加第二个扫描程序来修复 .
public class Average {
public static void main(String[] args) {
boolean flag = false;
do {
try {
System.out.println("Enter the number of integers you want to "
+ "calculate the average of: ");
Scanner input = new Scanner(System.in);
int value = input.nextInt();
int[] numbers = new int[value];
int sum = 0;
if( value == 0 ) {
throw new ArithmeticException();
}
boolean flag2 = false;
do{
try{
Scanner sc = new Scanner(System.in);
for( int i = 0; i < numbers.length; i++) {
System.out.println("Enter the " + (i+1) + " number: ");
numbers[i] = sc.nextInt();
sum += numbers[i];
flag2 = true;
}
} catch ( InputMismatchException e ) {
System.err.println("Cannot calculate average of non-numeric values.");
} catch ( NumberFormatException e) {
System.out.println("Cannot calculate average of non-numeric values.!!");
}
} while (!flag2);
double average = (double) sum / numbers.length;
System.out.println("The numbers you have entered are: " + Arrays.toString(numbers));
System.out.println("The sum of the numbers is: " + sum);
System.out.println("The number to divide by is: " + numbers.length);
System.out.println("The average of the numbers you have entered is: " + average);
flag = true;
} catch (InputMismatchException e) {
System.err.println("Input cannot be non-numeric values");
} catch (ArithmeticException e) {
System.err.println("Input can only be positive integers");
} catch (NegativeArraySizeException e) {
System.err.println("Input can only be positive integers");
}
} while (!flag);
}
}
2 回答
当用户输入非数字时,程序应该抛出NumberFormatException . 您需要与其他catch块一起处理该情况
只有在收到有效输入时,你才需要这样的东西来递增计数器 . 当收到错误输入时,请记得清除扫描仪缓冲区 .