Java 如何处理for循环内部的异常而不重新启动程序
我试图计算N个非负整数的平均值。我要求用户输入他们想要计算的平均数。然后让他们逐一输入数字。我还在do语句中使用try-and-catch,以便在用户输入错误值时再次提示用户 如果输入的N个数字中有一个不是整数,我如何重新提示用户。? 我所做的再次提示用户重新启动。我想知道一些方向 编辑:我使用相同的do while循环来捕捉输入是否为非数字。我现在得到的是无限数量的打印,打印错误并重新提示用户输入。我必须停止程序运行 编辑:问题是由于扫描仪未被清除。通过在嵌套的do while循环中添加第二个扫描仪进行修复Java 如何处理for循环内部的异常而不重新启动程序,java,while-loop,exception-handling,try-catch,java.util.scanner,Java,While Loop,Exception Handling,Try Catch,Java.util.scanner,我试图计算N个非负整数的平均值。我要求用户输入他们想要计算的平均数。然后让他们逐一输入数字。我还在do语句中使用try-and-catch,以便在用户输入错误值时再次提示用户 如果输入的N个数字中有一个不是整数,我如何重新提示用户。? 我所做的再次提示用户重新启动。我想知道一些方向 编辑:我使用相同的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);
}
}
当用户输入一个非数字时,程序应该抛出。您将需要处理该案例以及其他捕获块
} catch (NumberFormatExceptione) {
System.err.println("Input can only be only numbers");
}
只有在接收到有效输入时,才需要这样的方法来增加计数器。当接收到不正确的输入时,请记住清除扫描仪缓冲区
while (counter < numbers.length) {
try {
numbers[counter] = input.nextInt();
counter++;
} catch (InputMismatchException e) {
input.nextLine(); //This is to clear the scanner which is now holding the incorrect input
} catch (NumberFormatException e) {
input.nextLine();
}
}
System.out.println(Arrays.toString(numbers));
可能与@AndrewL重复。不是真的。如果不是整数,我可以处理用户输入,但我想知道的是,当用户在循环中输入非整数时,如何不重新启动整个过程。它处理非整数,但不会将它们重新提示到原来的点,而是重新启动。如果您已经在do while循环中执行了此操作,请在for上使用相同的方法loop@SamuelKok我试过了,用户被再次提示输入第一个号码。。任何提示?@wa7d使用while循环,并仅在成功插入时递增与数组索引对应的计数器。