2011-11-04 2 views
0

나는 간단한 자바 콘솔 게임을 쓰고있다. 스캐너를 사용하여 콘솔에서 입력을 읽습니다. 정수를 요구하는지 확인하려고하는데 문자가 입력되면 오류가 발생하지 않습니다.무한 루프를 일으키는 catch 블록을 사용 하시겠습니까?

boolean validResponce = false; 
int choice = 0; 
while (!validResponce) 
{ 
    try 
    { 
     choice = stdin.nextInt(); 
     validResponce = true; 
    } 
    catch (java.util.InputMismatchException ex) 
    { 
     System.out.println("I did not understand what you said. Try again: "); 
    } 
} 

하지만 그냥 catch 블록을 인쇄, 무한 루프를 만드는 것 : 나는 이것을 시도했다. 내가 도대체 ​​뭘 잘못하고있는 겁니까.

그리고 그래, 내가 새로운 자바

답변

4

nextInt() 일치하지 않는 출력을 폐기하지 않을 것이다; 프로그램은 매번 실패 할 때마다 반복해서 읽으려고 시도합니다. hasNextInt() 방법을 사용하여 nextInt()에 전화하기 전에 읽을 수있는 int이 있는지 확인하십시오.

hasNextInt()도 입력을 무시하기 때문에 정수가 아닌 InputStream에서 항목을 찾을 때 입력 스트림에서 다음 토큰을 테스트하기 만하면 nextLine()으로 지울 수 있는지 확인하십시오.

+0

브릴리언트의 일반적인 주제의

boolean isInValidResponse = true; //then while(isInValidResponse){ //makes more sense and is less confusing try{ //let user know you are now asking for a number, don't just leave empty console System.out.println("Please enter a number: "); String lineEntered = stdin.nextLine(); //as suggested in accepted answer, it will allow you to exit console waiting for more integers from user //test if user entered a number in that line int number=Integer.parseInt(lineEntered); System.out.println("You entered a number: "+number); isInValidResponse = false; } //it tries to read integer from input, the exceptions should be either NumberFormatException, IOException or just Exception catch (Exception e){ System.out.println("I did not understand what you said. Try again: "); } } 

사용해보십시오! 그래서 나는 모두 함께 try-catch를 제거 할 수 있습니다! –

+1

@ Adam8797 마찬가지로, hasNextInt()도 입력을 버리지 않으므로'nextLine()'을 사용하여 정수가 아닌 InputStream에서 항목을 찾으면 입력의 다음 토큰 만 테스트합니다 흐름. –

+0

고마워, 그게 좋은 팁. –

관련 문제