1

I'm trying to validate a user's input on a menu. Options are 1, 2, 3, and 4. I'm trying to handle the InputMismatchException error when they enter in a letter. I can't see what I'm doing wrong to make my code get stuck in an infinite loop.

    System.out.println("What will be your starting balance?");

    double startingBalance =0;
    boolean check = false;
    while(!check) {
        try {
            startingBalance = input.nextDouble();
            check = true;   
        }
        catch (InputMismatchException e) {
            System.out.println("Invalid input!");
            //startingBalance = 0;
            //e.printStackTrace();
            //check = false;
        }
    }

It looks like it get into the catch part, but loops through that repeatedly instead of going back to the try. I tried doing input.nextDouble();

to clear input buffer, but did nothing. Any help would be greatly appreciated.

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Nick M
  • 21
  • 4

2 Answers2

0

You can use input.nextLine(); to clear your Scanner in your catch block:

while (!check) {
    try {
        startingBalance = input.nextDouble();
        check = true;
    } catch (InputMismatchException e) {
        System.out.println("Invalid input!");
        input.nextLine();//this will clear your Scanner and repeat again
    }
}

Can I ask why you used nextLine() as opposed to nextDouble() ?

because nextLine move the Scanner to the next line

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

you need to set boolean check = false after first check and also use input.nestLine()

Anshul Sharma
  • 3,432
  • 1
  • 12
  • 17