为什么我的catch块会永远循环?

时间:2013-09-26 19:46:57

标签: java exception-handling while-loop try-catch

我正在做一个计算阶乘的程序,我写了一个捕获NumberFormatException和InputMismatchException的循环。 NumberFormatException运行正常并循环回try块,但InputMismatchException反复显示其消息而不循环回try块。我不确定我做错了什么。这是我的代码:

import java.util.*;

public class Factorial 
{
public static void main(String[] args) 
{
    Scanner s = new Scanner(System.in);
    System.out.println("Factorial Test Program\n");

    boolean success = false;

    while (!success)
    {   
        try
        {
            System.out.print("Enter an integer number: ");
            int number = s.nextInt();

            if (number < 0) throw new NumberFormatException();

            long f = number;

            for (int i = number-1; i>0; i--)
                f *= i;

            if (number==0) f=1;

            System.out.printf("The factorial of %s is %s.\n", number, f);
            success=true;

            System.out.println("Done!");
        }
        catch (NumberFormatException e)
        {
            System.out.println("Factorial of this value cannot be represented as an integer");
        }
        catch (InputMismatchException e)
        {
            System.out.println("You must enter an integer - please re-enter:");
        }
    }
}
}

2 个答案:

答案 0 :(得分:6)

输入无效整数后,s.nextInt()会不断地通过while循环传递换行符,并且该过程会自动重复 ad infinitum 。另一方面,当NumberFormatException发生时,已经读取了一个有效整数,因此没有换行符被传递到while循环。

s.nextLine()例外区块中添加InputMismatchException将解决此问题。

答案 1 :(得分:0)

在catch块中添加break;。 或者在try块中创建while循环

try {

    while() {

    }

} catch () { 

}
相关问题