2015-11-16 49 views
0

我只是想要得到age繼續在catch塊

有效int值從掃描儀獲取信息,但是,當用戶輸入一個字符串,爲什麼我不能再得到一個int?

這裏是我的代碼:

public static void getAge() throws InputMismatchException { 

    System.out.print("Enter Your age: "); 
    try { 
     age = in.nextInt(); 
    } catch (InputMismatchException imme) { 
     System.out.println("enter correct value for age:"); 
     in.nextInt(); // why this not works? 
    } 
} 

Enter Your age: hh 
enter correct value for age: 
Exception in thread "main" java.util.InputMismatchException 

我想請求,直到一個有效的輸入進入輸入有效的int值。

回答

1

如果nextInt()無法將輸入解析爲int,則會將輸入保留在緩衝區中。因此,下次您撥打nextInt()時,它正試圖再次讀取相同的垃圾值。你必須調用nextLine(),然後重試吃垃圾輸入:

System.out.print("Enter your age:"); 
try { 
    age = in.nextInt(); 
} catch (InputMismatchException imme) { 
    System.out.println("Enter correct value for age:"); 
    in.nextLine(); // get garbage input and discard it 
    age = in.nextInt(); // now you can read fresh input 
} 

你可能想在一個循環中也進行安排,這樣它會不斷地問反覆,只要輸入是不合適的:

System.out.print("Enter your age:"); 
for (;;) { 
    try { 
     age = in.nextInt(); 
     break; 
    } catch (InputMismatchException imme) {} 
    in.nextLine(); 
    System.out.println("Enter correct value for age:"); 
}