2017-11-07 1 views
0

나는 정수를 입력하도록 요청하고, 사용자의 경우에 사용자의 유형을 예를 들어 문자열을, 그 예외를 캐치하는 방법을 시작try/catch를 사용할 때 무한 루프를 피하는 방법은 무엇입니까?

public void askUserForStrategy(){ 

    try{ 

     System.out.println("What strategy do you want to use?\n"); 
     System.out.println("1 = Math.random\t  2 = System time\t " 
     + "3 = Sum of Math.random and System time"); 

     int strategy = sc.nextInt(); 

     selectStrategy(strategy); 

    } 

    catch(InputMismatchException Exception){ 

     System.out.println("That is not an integer. Try again.\n"); 
     askUserForStrategy(); 

    } 

} 

내가 그것을 수행 할 작업이 코드를 기본적으로되어 있습니다 다시 (사용자에게 정수 값을 입력하도록 요청하십시오). 그러나 사용자가 문자열을 입력 할 때 메서드가 반복됩니다.

+2

할 일을 계속 프로그램 흐름에'try-catch'를 사용하지 마십시오. 복구 할 수없는 예외 만 처리해야합니다. 같은 과정을 다시 시도하지 마십시오. – Filburt

답변

2

nextInt()이 예외를 throw하면 Scanner 개체는 다음 호출시 동일한 문자열을 사용하려고합니다.

try 내에 새로운 Scanner 개체를 할당 해보십시오. 또는 catch에서 nextLine()으로 전화를 걸어 불법적 인 행을 삭제합니다.

너무 많은 불법 입력 (너무 많지만 무한 시도가 이상적 인 경우) 후에 스택 오버플로가 발생하기 때문에이 방법은 좋지 않습니다.

try 본문 끝 부분에 do-whilereturn을 사용하는 것이 좋습니다.

+0

감사합니다! 메서드 내에서 스캐너 객체를 옮기고 완벽하게 작동했습니다. –

1

이 시도 :

public void askUserForStrategy() { 

for(int i=0; i<1; ++i) { 
    try{ 

    System.out.println("What strategy do you want to use?\n"); 
    System.out.println("1 = Math.random\t  2 = System time\t " 
    + "3 = Sum of Math.random and System time"); 

    int strategy = sc.nextInt(); 

    selectStrategy(strategy); 
    break; //break loop when there is no error 
    } 

    catch(InputMismatchException Exception){ 

    System.out.println("That is not an integer. Try again.\n"); 
    //askUserForStrategy(); 
    continue; //for clarity 

    } 
} 
} 
1

을 어쩌면 당신이

public void askUserForStrategy(){ 
Boolean loopFlag = true; 
while(loopFlag) { 
try{ 

    System.out.println("What strategy do you want to use?\n"); 
    System.out.println("1 = Math.random\t  2 = System time\t " 
    + "3 = Sum of Math.random and System time"); 

    int strategy = sc.nextInt(); 
    Integer.parseInt(strategy); 
    loopFlag = false; 
    selectStrategy(strategy); 
} 

catch(Exception e){ 

    //Parse has failed due to wrong input value, But loop will continue 

}}} 
0

처럼 뭔가를 찾고있는이 당신이 찾고있는 수 있습니다 ..

public void askUserForStrategy() { 
     while (true) { 
      try { 
       Scanner sc = new Scanner(System.in); 
       System.out.println("What strategy do you want to use?\n"); 
       System.out.println("1 = Math.random\t  2 = System time\t " + "3 = Sum of Math.random and System time"); 

       int strategy = sc.nextInt(); 
       System.out.println("Selected strategy : " +strategy); 
       break; 
      } catch (Exception e) { 
       System.out.println("That is not an integer. Try again.\n"); 
       continue; 
      } 
     } 
     // selectStrategy(strategy); 
    } 

사용자가 문자열을 선택하는 경우 , 다시 옵션을 묻습니다.

사용자가 정수를 선택하면210

는, 다음은 사용자가 선택한 전략 옵션을 가지고 프로그램 흐름 .. (수단은 휴식의 도움으로 while 루프에서 나온 후 호출 selectStrategy 방법)

감사

관련 문제