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