2012-04-07 78 views
1

所以我有這樣的代碼:如何修復InputMismatchException時

protected void giveNr(Scanner sc) { 
    //variable to keep the input 
    int input = 0; 
    do { 
     System.out.println("Please give a number between: " + MIN + " and " + MAX); 
     //get the input 
     input = sc.nextInt(); 
    } while(input < MIN || input > MAX); 
} 

如果人力投入某事那不是一個整數,說一個字母或一個字符串,程序崩潰,並給出了錯誤,InputMismatchException。我該如何解決這個問題,以便在輸入錯誤類型的輸入時,人們再次被要求輸入(並且程序不會崩潰?)

回答

2

您可以捕獲InputMismatchException,打印一條錯誤消息告訴用戶出了什麼問題,並再次繞過迴路:

int input = 0; 
do { 
    System.out.println("Please give a number between: " + MIN + " and " + MAX); 
    try { 
     input = sc.nextInt(); 
    } 
    catch (InputMismatchException e) { 
     System.out.println("That was not a number. Please try again."); 
     input = MIN - 1; // guarantee we go around the loop again 
    } 
while (input < MIN || input > MAX)