2013-09-26 2 views
2

나는 계승을 계산하는 프로그램을하고 있으며 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:"); 
     } 
    } 
} 
} 
+2

하지 당신이 블록 영원히 반복을 잡을하지만 –

+2

... 루프 동안 성공적인 적이있어 없기 때문에 try 블록 내부의 while 루프를 만들거나. –

+0

블록 루핑 중 전체가 아니며, 그것은 단지 반복적 인 InputMismatchException 블록의 내용 일뿐입니다. while 루프의 시작 부분으로 다시 루프하면 괜찮을 것입니다. – user1923768

답변

6

잘못된 정수 s.nextInt()를 입력하면 지속적으로 while 루프를 통해 개행 문자를 통과하는 과정은 그 자체 무한히를 반복합니다. 반면에 NumberFormatException이 발생하면 유효한 정수가 이미 읽혀 지므로 while 루프에 전달되는 개행 문자가 없습니다.

InputMismatchException 예외 블록 내에 s.nextLine()을 추가하면이 문제가 해결됩니다.

+0

다른 루프가 영원히 멈추는 동안 한 가지 예외가 정상적으로 작동하는 이유는 무엇입니까? – user1923768

+0

'NumberFormatException'이 발생하면 이미 성공적으로 정수를 읽었으므로'while' 루프로 전달되는 개행 문자가 없습니다. – Reimeus

+0

그래, 예외적으로 s.nextInt()가 실패하고 입력 버퍼 변화하지 않습니까? 그래서 기본적으로 무언가를 입력 할 기회가 오기 전에 자동으로 무효 한 데이터를 입력하고 있습니까? 그래도 "정수 ​​값 입력 :"을 볼 수 없어야합니까? 나는하지 않는다. 그것은 단지 "정수를 입력해야합니다 - 다시 입력하십시오 :"반복해서. – user1923768

0

catch 블록에 break;을 추가하십시오. 는

try { 

    while() { 

    } 

} catch() { 

} 
관련 문제