我正在做一個計算階乘的程序,我寫了一個循環來捕獲NumberFormatException和InputMismatchException。 NumberFormatException運行良好並循環回到try塊,但InputMismatchException一遍又一遍地顯示其消息,而沒有循環返回到try塊。我不確定我做錯了什麼。這裏是我的代碼:爲什麼我的catch塊永遠循環?
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:");
}
}
}
}
不是你catch塊循環永遠但while循環... –
因爲你永遠都不會成功。 –
不是整個塊循環時,它只是InputMismatchException塊的內容永遠循環。如果它循環回到while循環的開始,那就沒問題了。 – user1923768