1

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);
4

1 回答 1

7

您需要sc.nextLine()catch块中清除错误输入。如果nextInt()输入与 int 模式不匹配,调用会将输入留在缓冲区中。

于 2013-07-01T14:41:24.907 回答