在while循环中多次尝试捕获

时间:2015-05-15 11:51:19

标签: java try-catch

希望有人可以提供帮助。拖网几天,无法找到解决方案。尝试使用while / try / throw创建catch循环以进行异常处理,但需要捕获多个异常。

我已经尝试过几乎所有我能想到的事情或者它不会出现在循环中,或者它会跳过剩下的代码(没有粘贴在这里)并完成程序。

Scanner scanner = new Scanner(System.in);
boolean NotCorrectInput = false;
howManyToAdd = 0;

while (!NotCorrectInput) {
    try {
        System.out.println("How many products would you like to add?");
        howManyToAdd = scanner.nextInt();
        NotCorrectInput = true;
        }
    catch (InputMismatchException e){
        System.err.println("You have not entered the correct number format. Please try again.");
        }

    try {
        if (howManyToAdd < 1) {
        throw new NegativeArraySizeException();
        }
        } 
    catch (NegativeArraySizeException e) {
        System.err.println("You have not entered a possitive number. Please try again.");
        }

    }

    SecondProduct lp[] = new SecondProduct[howManyToAdd];
 //Rest of code from here on down.

我希望它能期望int,但是如果它传递了doublefloat那么它将在循环中处理它并继续运行直到它传递{ {1}},但如果给出一个负数来开始数组,那么它将循环回到开始并要求传递正int

3 个答案:

答案 0 :(得分:2)

您不需要抛出任何异常:

while (!NotCorrectInput) {
    try {
        System.out.println("How many products would you like to add?");
        howManyToAdd = scanner.nextInt();
        if (howManyToAdd >= 1)
            NotCorrectInput = true;
        else 
            System.err.println("You have not entered a positive number. Please try again.");
    }
    catch (InputMismatchException e) {
        System.err.println("You have not entered the correct number format. Please try again.");
        scanner.next();
    }
}

BTW,NotCorrectInput是一个令人困惑的名字,因为当输入正确时你实际上将它设置为true。

答案 1 :(得分:0)

while (!NotCorrectInput) {
    try {
        System.out.println("How many products would you like to add?");
        howManyToAdd = scanner.nextInt();
        NotCorrectInput = true;
        if (howManyToAdd < 1) {
        System.err.println("You have not entered a possitive number. Please try again.");
        }

       }
    catch (InputMismatchException e){
        System.err.println("You have not entered the correct number format. Please try again.");
        }


    }

这就是你如何做多次尝试捕捉!

答案 2 :(得分:-1)

稍微调整一下你的代码:

Scanner scanner = new Scanner(System.in);
boolean CorrectInput = false;
howManyToAdd = 0;

while (!CorrectInput) {
    try {
        System.out.println("How many products would you like to add?");
        howManyToAdd = scanner.nextInt();
        if (howManyToAdd < 1) {
            throw new NegativeArraySizeException();
        }
        else
            CorrectInput = true;
    }
    catch (InputMismatchException e){
        System.err.println("You have not entered the correct number format. Please try again.");
    }    
    catch (NegativeArraySizeException e) {
        System.err.println("You have not entered a possitive number. Please try again.");
    }
}