2014-10-20 103 views
0

我試圖用此代碼來完成的所有操作都是檢查用戶的輸入是否爲整數,然後如果它不是正確的數據類型,則再次輸入3次機會。然後最後拋出一個例外,如果他們達到「maxTries」標記。Java嘗試捕獲問題

任何幫助將不勝感激。乾杯。

boolean correctInput = false;  
    int returnedInt = 0; 
    int count = 0; 
    int maxTries = 3; 

    Scanner kybd = new Scanner(System.in); 

    while(!correctInput) 
    { 
     try 
     { 
      System.out.println("\nInput your int, you have had:" + count + " tries"); 
      returnedInt = kybd.nextInt(); 
      correctInput = true; 

     } 
     catch(InputMismatchException e) 
     { 
      System.out.println("That is not an integer, please try again.."); 
      if (++count == maxTries) throw e; 

     } 

    } 
    return returnedInt; 
+2

你對這段代碼有什麼問題?錯誤訊息?它不是做它應該做的事情,如果是這樣,它做什麼呢? – JJJ 2014-10-20 17:26:08

+0

我想你沒有設置correctInput爲false,所以它跳出循環 – 2014-10-20 17:27:13

+0

字符串 這不是整數的,請稍後再試.. 輸入您的INT,您有:1次嘗試 異常線程「main 「java.util.InputMismatchException 這不是一個整數,請重試.. 輸入您的INT,你所擁有的:2次嘗試 這不是一個整數,請重試.. \t在java.util.Scanner中.throwFor(Scanner.java:909) \t at java.util.Scanner.next(Scanner.java:1530) \t at java.util.Scanner.nextInt(Scanner.java:2160) \t在java.util.Scanner.nextInt(Scanner.java:2119) \t在Main.inputInt(Main.java:25) \t在Main.main(Main.java:10) Java結果:1個 BUILD SUCCESSFUL(總時間:5秒) – user258873 2014-10-20 17:27:38

回答

2

發生這種情況的原因是因爲您的掃描儀緩衝區未被清除。輸入kybd.nextInt()已經填充了一個非int值,但是由於它在讀取時失敗了,它實際上並沒有從堆棧中清除掉。因此,第二個循環嘗試再次填充已填充的緩衝區,這已經是錯誤的了。

要解決此問題,您可以在異常處理中使用nextLine()清除緩衝區。

 } catch (InputMismatchException e) { 
      System.out 
        .println("That is not an integer, please try again.."); 
      kybd.nextLine(); //clear the buffer, you can System.out.println this to see that the stuff you typed is still there 
      if (++count == maxTries) 
       throw e; 

     } 

另一種方法是使用String s = kybd.nextLine()並解析整數並從而是捕獲該異常。

+0

我很滿意爲-1取一丁,但它會幫助我解釋爲什麼它值得-1。 – Compass 2014-10-20 17:48:52

+0

非常感謝!這工作了治療歡呼=) – user258873 2014-10-20 17:54:05

+0

要驗證這一點,請在您的catch子句中添加一行:System.out.println(「input was:」+ kybd.next());' - 您會看到錯誤的輸入仍在隊列中。具有諷刺意味的是,這將清除問題... :) – 2014-10-20 17:55:47