2011-11-04 112 views
0

我正在写一个简单的java控制台游戏。我使用扫描仪从控制台读取输入。我试图验证它是否需要一个整数,如果输入了一个字母,我不会收到错误。我试过这个:尝试catch块导致无限循环?

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

回答

4

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

确保当你发现在InputStream其他东西比一个整数你清楚它与nextLine()因为hasNextInt()也不会丢弃输入,它只是测试的输入流中的下一个标记。

+0

辉煌共同话题!所以我可以摆脱所有的一起尝试赶上! –

+1

@ Adam8797同样,当你在InputStream中找到一些不是整数的东西时,你可以用'nextLine()'清除它,因为'hasNextInt()'也不会丢弃输入,它只是测试输入中的下一个标记流。 –

+0

谢谢,这是一个很好的提示。 –

0

尝试使用

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 conditionalshttps://blog.jetbrains.com/idea/2014/09/the-inspection-connection-issue-2/