我試圖計算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循環中使用相同的方法 –