2010-11-15 46 views
0

我有我正在使用的以下代碼讓用戶輸入一個整數,檢查以確保輸入有效,如果沒有,請再次輸入。當代碼運行時,一切正常,直到給出一些無效的輸入爲止,此時代碼會循環而不會暫停,直到發生堆棧溢出時再次請求輸入,我不知道爲什麼。代碼:爲什麼這種獲取用戶輸入的方法不起作用?

//Create the scanner object 
private static Scanner in = new Scanner(System.in); 

//Function to get input in integer form, complete with exception handling 
//A value of -1 means the user is done inputing 
public static int getInt() 
{ 
    int num; 

    //Begin try block 
    try 
    { 
     //Get the user to input an integer 
     num = in.nextInt(); 

     //Make sure the integer is positive. Throw an exception otherwise 
     if (num < -1) 
      throw new InputMismatchException(); 
    } 

    //If an exception occurred during the inputting process, recursively call this function 
    catch (InputMismatchException e) 
    { 
     System.out.println("Error: Input must be a positive integer, or -1."); 
     System.out.print("Enter a score: "); 
     num = getInt(); 
    } 

    //Return the inputed number 
    return num; 
} 

回答

3

當掃描器拋出InputMismatchException時,掃描儀將不 傳遞引起異常,這樣它可以被檢索 或通過某些其它方法

所以sayeth的Javadoc跳過令牌,即不是數字的字符串不會自動從輸入中刪除。手動調用in.next()以放棄它。

+0

+1不錯的鏡頭''' – 2010-11-15 19:12:31

+0

修復了它。非常感謝! – Lewis 2010-11-15 19:14:24

0

該函數是否需要遞歸?似乎這應該很容易做到簡單的循環。

0

getInt() - >如果(NUM < -1)拋出異常() - >捕獲(例外) - > NUM = getInt()

你怎麼能指望循環?

1

你應該叫next();調用nextInt();再次之前跳過無效的輸入。

相關問題