Catching an InputMismatchException until it is correct

exception, java, loops

Solution

Be aware that `When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.`

To avoid "infinite loop of "Customer IDs are numbers only".", You need to call `input.next();` in the catch statement to to make it possible to re-enter number in Console

From

statement

catch (InputMismatchException e) {
            System.out.println("Customer IDs are numbers only");

To

catch (InputMismatchException e) {
            System.out.println("Customer IDs are numbers only");
            input.next();
        }

Example tested:

Enter Customer ID: a
Customer IDs are numbers only
b
Customer IDs are numbers only
c
Customer IDs are numbers only
11

Problem

I am trying add catch blocks to my program to handle input mismatch exceptions. I set up my first one to work inside of a do while loop, to give the user the opportunity to correct the issue. ``` System.out.print("Enter Customer ID: "); int custID=0; do { try { custID = input.nextInt(); } catch (InputMismatchException e){ System.out.println("Customer IDs are numbers only"); } } while (custID<1); ``` As it stands, if I try to enter a letter, it goes into an infinite loop of "Customer IDs are numbers only". How do I make this work properly?

Original source

Related problems