2011-11-04 137 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/