我有我正在使用的以下代碼讓用戶輸入一個整數,檢查以確保輸入有效,如果沒有,請再次輸入。當代碼運行時,一切正常,直到給出一些無效的輸入爲止,此時代碼會循環而不會暫停,直到發生堆棧溢出時再次請求輸入,我不知道爲什麼。代碼:爲什麼這種獲取用戶輸入的方法不起作用?
//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;
}
+1不錯的鏡頭''' – 2010-11-15 19:12:31
修復了它。非常感謝! – Lewis 2010-11-15 19:14:24