2015-04-23 51 views
0

我想捕獲任何不是Int的輸入,並提示輸入有效的輸入3次。 3次後,該計劃將繼續並要求另一個評級。我似乎無法重複try/catch塊,甚至無法捕獲InputMismatchException。有什麼建議麼?使用InputMismatchException try/catch塊

do { 
    //prompt for rating 
     try { 
     System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): "); 
     //capture 
      rating = response.nextInt(); 
     } catch (InputMismatchException err) { 
      System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: "); 
      rating = response.nextInt(); 
     } //end catch 
    } while (rating >= 0); 
+0

添加某種形式的'counter'之外的'做,while'循環,初始化爲'0',在'catch'塊中,遞增'counter'並將'rating'設置爲'-2'。 – MadProgrammer

回答

0

你既可以做一個循環:

int count = 0; 
do { 
    //prompt for rating 
     try { 
     System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): "); 
     //capture 
      rating = response.nextInt(); 
     } catch (InputMismatchException err) { 
      System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: "); 
      count++; 
     } //end catch 
    } while (rating >= 0 && count < 3); 

或者使用嵌套的try/catch:

do { 
    //prompt for rating 
     try { 
     System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): "); 
     //capture 
      rating = response.nextInt(); 
     } catch (InputMismatchException err) { 
      System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: "); 
      try { 
     System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): "); 
     //capture 
      rating = response.nextInt(); 
     } catch (InputMismatchException err) { 
      System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: "); 
      rating = response.nextInt(); 
     } //end catch 
     } //end catch 
    } while (rating >= 0); 

個人而言,我更喜歡第一種方法。

我想這個代碼,並運行,沒有任何例外:

公共類主要{

public static void main(String[] args) throws IOException { 
    int count = 0; 
    int rating = 0; 
    do { 
     Scanner response = new Scanner(System.in); 
     //prompt for rating 
      try { 
      System.out.println("Enter a rating between 0-4 for the Movie of the Week (Enter -1 to stop/exit): "); 
      //capture 
       rating = response.nextInt(); 

      } catch (InputMismatchException err) { 
       System.out.println("Invalid input. Please enter a rating 0-4 or enter -1 to exit: "); 
      } finally { 
       count++; 
       System.out.println("Rating-->" + rating); 
      } 
     } while (rating >= 0 && count < 3); 

} 

}

+0

我的程序仍然會拋出一個InputMismatchException錯誤,即使我抓住它並提示輸入另一個評級。任何想法,爲什麼這是? –

+0

我確實最終使用了第一個建議,但爲了提示它3次。 –

+0

我只是試了一段代碼,它沒有任何異常就跑了。 – Phoenix