尝试catch阻塞导致无限循环?

我正在写一个简单的java控制台游戏。 我使用扫描仪从控制台读取输入。 我试图validation它我要求一个整数,如果输入一个字母,我不会收到错误。 我试过这个:

boolean validResponce = false; int choice = 0; while (!validResponce) { try { choice = stdin.nextInt(); validResponce = true; } catch (java.util.InputMismatchException ex) { System.out.println("I did not understand what you said. Try again: "); } } 

但它似乎创建了一个无限循环,只是打印出catch块。 我究竟做错了什么。

是的,我是Java新手

nextInt()不会丢弃不匹配的输出; 该程序将尝试一遍又一遍地读取它,每次都失败。 使用hasNextInt()方法确定在调用nextInt()之前是否可以读取int

确保当您在InputStream找到除整数之外的其他内容时,使用nextLine()清除它,因为hasNextInt()也不会丢弃输入,它只是测试输入流中的下一个标记。

尝试使用

 boolean isInValidResponse = true; //then while(isInValidResponse){ //makes more sense and is less confusing try{ //let user know you are now asking for a number, don't just leave empty console System.out.println("Please enter a number: "); String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user //test if user entered a number in that line int number=Integer.parseInt(lineEntered); System.out.println("You entered a number: "+number); isInValidResponse = false; } //it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception catch (Exception e){ System.out.println("I did not understand what you said. Try again: "); } } 

因为avoiding negative conditionals的共同话题https://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/