Java 尝试循环捕获(InputMismatchException和ArrayIndexOutOfBoundsException之间的差异)

Java 尝试循环捕获(InputMismatchException和ArrayIndexOutOfBoundsException之间的差异),java,arrays,indexoutofboundsexception,inputmismatchexception,Java,Arrays,Indexoutofboundsexception,Inputmismatchexception,我有这个密码 package example; import java.util.InputMismatchException; import java.util.Scanner; public class Example { public static void main(String[] args) { Scanner input = new Scanner(System.in); int rep; int[] arraya = new int[2];

我有这个密码

package example;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Example {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int rep;
    int[] arraya = new int[2];
    do {
        try {
            rep = 0;
            System.out.print("input col :");
            int kol = input.nextInt();
            System.out.print("input value :");
            int val = input.nextInt();
            arraya[kol] = val;
        } catch (InputMismatchException e) {
            System.out.println("input must integer");
            rep = 1;
            input.next();
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("out of range");
            rep = 1;
        }
    } while (rep == 1);
}
}
为什么我必须添加
input.next()
捕获中(输入不匹配异常e)以避免无休止的循环

为什么在
catch中(arrayindexoutofboundsexceception e)不需要
输入。下一步()以避免无休止的循环


catch中(ArrayIndexOutOfBoundsException e),循环运行良好,无需
输入为什么它不同于捕获(输入不匹配异常e)

因为如果输入非整数字符,
int kol=input.nextInt()
不会等待用户再次输入
int
,它将继续尝试读取以前输入的字符,因为它没有被使用


如果您输入一个越界
int
,它将被消耗,并且在下一次迭代中读取下一个
int

您不应该捕捉到
阵列索引超出边界异常
。您应该修复导致它的错误。@EJP感谢您的回复,我编写了该代码以了解
ArrayIndexOutOfBoundsException
InputMismatchException
在循环中处理不同的原因