2015-04-23 64 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