Pedro Costa
Pedro Costa

Reputation: 437

Why do I have a never-ending do-while loop?

I have a non-working do-while loop. When I enter a String instead of an int, it should say "bla" and ask again to insert a number, but instead it sends the message text over and over again. What's wrong in this code?

    boolean i = true;
    do {
       i = false;  

       try {
           System.out.println("insert number");
           int k = sc.nextInt();  
       }
       catch(InputMismatchException e) {
           System.out.println("test");
           i = true;
       } 
   } while ( i== true);

Upvotes: 1

Views: 623

Answers (1)

Russell Zahniser
Russell Zahniser

Reputation: 16364

You need to do sc.nextLine() in the catch block to clear the erroneous input. The nextInt() call will leave the input in the buffer if it does not match the int pattern.

Upvotes: 6

Related Questions