try catch on looping(InputMismatchException 和 ArrayIndexOutOfBoundsException 之间的区别)

try catch on looping (differnet between InputMismatchException and ArrayIndexOutOfBoundsException)

我有这个代码

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);
}
}

为什么我必须在 catch(InputMismatchException e); 中添加 input.next(); 以避免无限循环?

为什么在catch(ArrayIndexOutOfBoundsException e);中不需要input.next();来避免死循环?

catch(ArrayIndexOutOfBoundsException e);中,没有input.next();循环运行良好,为什么它与catch(InputMismatchException e);不同?

因为如果你输入一个非整数字符,int kol = input.nextInt();不会等待用户再次输入一个int,它会保留试图读取之前输入的字符,因为它没有被消耗。

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