2014-02-24 69 views
0

不知道如何實現不匹配例外。當它應該是一個int並且沒有程序崩潰時,如何鍵入一個字母?不匹配例外問題

try { 
    System.out.print("Enter graduation year : "); 
    year = response.nextInt(); 
} catch (InputMismatchException ex) { 
    while (year < 1920 || year > 2010) { 
    System.out.print("invalid value. Enter a year between 1920 and 2010 : "); 
    year = response.nextInt(); 
} 

回答

2

不,您不希望在catch塊中得到您的輸入,而是想警告用戶在該塊中輸入錯誤。相反,在掃描器的nextInt()之後,在try塊中設置一個布爾值。在while循環中圍繞整個事物,並且只有在布爾成功設置時才退出while循環。

僞代碼:

initialize boolean variable, inputStillBad to true. 
while inputStillBad 
    try block 
    prompt user for input 
    get input from scanner 
    if this line was reached, then scanner succeeded 
    check if year is within bounds, and if so: 
     set inputStillBad to false. 
    else: 
     warn user that the year was out of range 
    catch your exception here 
    warn the user that they entered non-numeric input 
end while loop 
+0

真棒感謝。 – user3344218

+0

@ user3344218:不客氣! –

+0

@ user3344218:查看編輯 –

1

可以檢查用戶輸入的詮釋如下:

if(response.hasNextInt()) 
{ 
year = response.nextInt(); 
} 
+0

酷感謝很多 – user3344218

+0

不客氣! – Kakarot