2016-09-14 44 views
1

我是Java新手,想問您一個問題。Java Try-catch塊,Catch塊不會再提示用戶輸入新值

我寫了下面的代碼,其中「numOfThreads」應由用戶通過控制檯分配一個有效的int值。

但是,如果輸入不正確並且我們進入catch塊,應該重新提示用戶輸入「numOfThreads」,直到它的類型和範圍都是正確的。

出於某種原因,我似乎進入了無限循環。你能協助嗎?謝謝:)

import java.util.Scanner; 

public class Main { 

    public static void main(String args[]){ 

     int numOfThreads; 
     boolean promptUser = true; 

     Scanner keyboard = new Scanner(System.in); 

     while (promptUser) 
     { 
      try{ 
       numOfThreads = keyboard.nextInt(); 
       promptUser = false; 
      } 
      catch(Exception e){ 
       System.out.println("Entry is not correct and the following exception is returned: " + e); 
       numOfThreads = keyboard.nextInt(); // DOES NOT SEEM TO BE ASKING FOR A NEW INPUT 
      } 
     } 
    } 
} 
+1

如果'nextInt()'拋出一個異常,它不會消耗令牌......所以再次調用'nextInt'就會再次拋出。 –

+0

你的try/catch很無用......如果他們在重新提示時輸入錯誤的輸入會怎麼樣? – Li357

回答

3

它doesn't因爲nextInt嘗試消耗的最後一個令牌。當輸入無效時,不能使用它。結果,以下的nextInt調用也不會消耗它。在numOfThreads = keyboard.nextInt();之前寫上keyboard.nextLine,你很好。

catch(Exception e){ 
    System.out.println("Entry is not correct and the following exception is returned: " + e); 
    // this consumes the invalid token now 
    keyboard.nextLine(); 
    numOfThreads = keyboard.nextInt(); // It wasn´t able to get the next input as the previous was still invalid 
    // I´d still rewrite it a little bit, as this keyboard.nextInt is now vulnerable to throw a direct exception to the main 
}