나는 계승을 계산하는 프로그램을하고 있으며 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:");
}
}
}
}
하지 당신이 블록 영원히 반복을 잡을하지만 –
... 루프 동안 성공적인 적이있어 없기 때문에 try 블록 내부의 while 루프를 만들거나. –
블록 루핑 중 전체가 아니며, 그것은 단지 반복적 인 InputMismatchException 블록의 내용 일뿐입니다. while 루프의 시작 부분으로 다시 루프하면 괜찮을 것입니다. – user1923768