Mark E
Mark E

Reputation: 3483

Infinite loop with java code, Scanner object buffer may be

I'm trying to read a number for a switch case option but I'm stuck with an exception. I will try to explain the problem better in code:

do{
    try{
        loop=false;
        int op=teclado.nextInt();
        //I tryed a teclado.nextLine() here cause i saw in other Q but didn't work
    }
    catch(InputMismatchException ex){
        System.out.println("Invalid character. Try again.");
        loop=true;//At the catch bolck i change the loop value
    }
}while(loop);//When loop is true it instantly go to the catch part over and over again and never ask for an int again

When I type an int it works perfectly, but the exception makes it start over. The second time, the program does not ask for the int (I think it could be a buffer and I need something like fflush(stdin) in C), and the buffer just starts writing like crazy.

Upvotes: 0

Views: 392

Answers (1)

Makoto
Makoto

Reputation: 106440

You would be well-served creating a new instance of Scanner from within the catch to get the input should you fail. EDIT: You can use a Scanner.nextLine() to advance past the newline character when you fail. A do...while loop may be inappropriate for this, since it guarantees that it will execute at least once.

A construct that may help you out more is a simple while loop. This is actually a while-true-break type of loop, which breaks on valid input.

while(true) {
    try {
        op=teclado.nextInt();
        break;
    } catch(InputMismatchException ex){
        System.out.println("Invalid character. Try again.");
        teclado.nextLine();
    }
}

Upvotes: 1

Related Questions