我正在做一个计算阶乘的程序,我编写了一个循环来捕获 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:");
}
}
}
}