使用InputMismatchException尝试/ catch块

时间:2015-04-23 03:39:02

标签: java try-catch

我想捕获任何不是Int的输入并提示有效输入3次。 3次之后,程序将继续进行并要求另一个评级。我似乎没有try / catch块重复甚至捕获InputMismatchException。有什么建议吗?

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);

1 个答案:

答案 0 :(得分: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 class Main {

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);

}

}