0

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?

Argemione
  • 121
  • 2

1 Answers1

1

(I figured out the answer while reviewing the question. Maybe this can help others)

Since an exception is raised by this instruction int k = scanner.nextInt(); this instruction is not completed, and hence, the "next" element of "System.in" is still the same (which is "a" in example (2)). Consequently, it raises the same exception endlessly.

To fix it, I simply had to add scanner.nextLine(); in the catch statement, which causes the program to ask for a new user input.

Argemione
  • 121
  • 2