N
N
NameOf Var2017-08-01 23:03:54
Java
NameOf Var, 2017-08-01 23:03:54

Does the program loop when handling the exception (InputMismatchException) thrown by Scanner?

Posted the code below. If you deliberately enter text instead of a number in the console, then the program loops and endlessly handles the InputMismatchException exception

for (int i = 0; i < Count; i++) {

            System.out.println("Enter the number");
            try {
                userNumber = in.nextInt();
                if (!(userNumber > 0 && userNumber < 11))
                    throw new Exception("The number must be greater than 1 and less than 10. ");
            }
            catch (InputMismatchException err) {
                System.out.println("Type a number, not a text");
                i--;
                continue;
            }
            catch (Exception err) {
                System.out.println(err.getMessage());
                i--;
                continue;
            }

Outputs something like this:
Enter the number
asdasd
Type a number, not a text
Enter the number
Type a number, not a text
Enter the number
Type a number, not a text
Enter the number, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
1
1001001, 2017-08-02
@hax

Scaner tries to read the previously entered string (expecting int), catches an exception and tries to read it again.
If you want to keep your code, add in.next() to catch blocks
but it's better to use hasNextInt() and either read int or print message and read String

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question