0
do{
    try{
        System.out.println("Please enter the publication year :");
        year=keyboard.nextInt();
        doneYear=true;
    } catch(InputMismatchException e) {
        System.out.println("Please enter a number.");
    }
} while(!doneYear);

This doesn't work. It loops infinitely once I hit the first exception.

Mureinik
  • 252,575
  • 45
  • 248
  • 283
David Benalal
  • 75
  • 1
  • 2
  • 7

1 Answers1

1

The nextXYZ() methods (and specifically nextInt() in your case) don't consume a token if they fail with a InputMismatchException. If that occurs, you need to consume the current, erroneous, token in order to proceed and get a new one. Otherwise, you'd just keep re-evaluating, a re-failing the same input, resulting in an infinite loop as you observed:

do {
    try {
        System.out.println("Please enter the publication year :");
        year = keyboard.nextInt();
        doneYear = true;
    } catch (InputMismatchException ignore) {
        keyboard.nextLine(); // consume and ignore current input
        System.out.println("Please enter a number.");
    }
} while (!doneYear);
Mureinik
  • 252,575
  • 45
  • 248
  • 283