The desired behavior of the code is the following: The user is asked for an input. While they provide incorrect input, they're asked again, until they finally enter a valid value.
Here is a minimal example:
int[] t = new int[2];
Scanner scanner = new Scanner(System.in);
while (true) {
try {
int k = scanner.nextInt();
System.out.println(t[k]);
break;
} catch (Exception e) {
System.out.println(e);
}
}
scanner.close();
(1) If the user types "-1", the corresponding exception (namely "java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 2") is printed, after what they have to type again (just as intended).
(2) However, if the user types "a", the corresponding exception (namely "java.util.InputMismatchException") is printed endlessly.
So, can you explain why/how the Scanner class is causing the problem, and how to solve it?