2014-03-29 26 views
0

我讀過的用戶輸入必須只有int類型,問題出現在用戶輸入字母而不是int時。我知道如何處理異常,但我想將掃描儀返回到用戶犯了錯誤的地方。我能怎麼做? 我已經嘗試過無限循環,但它不起作用。用戶錯誤後回掃描器 - java

try{ 
    System.out.print("enter number: "); 
    value = scanner.nextInt(); 
}catch(InputMismatchException e){ 
    System.err.println("enter a number!"); 
} 
+0

你能告訴我們你的循環嘗試嗎? – PakkuDon

回答

2

而其他的答案給你使用的循環,你應該避免使用異常作爲你的基本邏輯的一部分正確的思想。相反,您可以使用ScannerhasNextInt來檢查用戶是否傳遞了整數。

System.out.print("enter number: "); 
while (!scanner.hasNextInt()) { 
    scanner.nextLine();// consume incorrect values from entire line 
    //or 
    //tastiera.next(); //consume only one invalid token 
    System.out.print("enter number!: "); 
} 
// here we are sure that user passed integer 
int value = scanner.nextInt(); 
+0

耶!這是我正在尋找的,謝謝! – user3344186

2

循環是正確的想法。你只需要標記成功和發揚:

boolean inputOK = false; 
while (!inputOK) { 
    try{ 
     System.out.print("enter number: "); 

     numAb = tastiera.nextInt(); 

     // we only reach this line if an exception was NOT thrown 
     inputOK = true; 
    } catch(InputMismatchException e) { 
     // If tastiera.nextInt() throws an exception, we need to clean the buffer 
     tastiera.nextLine(); 
    } 
} 
+0

我想你應該在catch塊中添加'tastiera.nextLine();'。因爲當'Scanner'引發異常時,它不會讀取任何內容。所以如果用戶輸入一個無效的行,你的循環將永不結束 – locoyou

+0

@locoyou良好的捕獲,謝謝。固定。 – Mureinik