我试图计算N个非负整数的平均值。我要求用户输入他们想要计算的平均数。然后让他们逐个输入数字。我也在try语句中使用try和catch,以便在输入错误值的情况下再次提示用户。如何处理循环内的异常,并没有程序重新启动
如果输入的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);
}
}
的可能的复制[如何循环的用户输入,直至一个整数被输入?](http://stackoverflow.com/questions/19130217/how-to-loop-user-input-until-an-integer - 被输入) – Li357
@AndrewL。不是真的。我能够处理用户输入,如果它不是整数,但我想知道的是当用户在循环内输入非整数时,如何不重新启动整个事情。它处理非整数,但它不会重新提示它们到它们的位置,而是重新启动 – wa7d
,您已在“do while”循环中完成它,在for循环中使用相同的方法 –