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

mor*_*apg 2 java exception-handling try-catch while-loop

我正在做一个计算阶乘的程序,我写了一个捕获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:");
        }
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*eus 6

一旦输入了无效的整数,就会s.nextInt()不断地通过while循环传递换行符,并且该过程无限地重复.另一方面,当NumberFormatException发生时,已经读取了有效整数,因此没有换行符传递给while循环.

s.nextLine()InputMismatchException异常块中添加将纠正此问题.