2017-12-17 39 views
0

정수를 검사하고 사용자가 17 이상의 정수를 올바르게 입력 할 때까지 루핑을 계속하는 함수를 만들려고합니다. 그러나 잘못된 입력 ('K'또는 '&')을 입력하면 무한 루프에 빠질 수 있습니다. 나는 또한 내 캐치에 재귀를 사용하고올바른 입력을 얻기 위해 try 및 catch를 반복하는 방법은 무엇입니까?

불러 :

public static int getAge(Scanner scanner) { 
    int age; 
    boolean repeat = true; 

    while (repeat) { 
     try 
     { 
      System.out.println("Enter the soldier's age: "); 
      age = scanner.nextInt(); 
      repeat = false; 
     } 
     catch(InputMismatchException exception) 
     { 
      System.out.println("ERROR: You must enter an age of 17 or higher"); 
      repeat = true; 
     } 
    } 
    return age; 
} 
+1

가능한 중복 : 이것은 당신이 nextInt()를 호출 다음에, 그것은 동일한 오래된 쓰레기 대신 작업 할 새로운 데이터가있을 것이라는 점을 보장합니다 잘못된 데이터 입력 (Java)] (https://stackoverflow.com/questions/27208796/trying-to-use-try-catch-in-a-while-loop-until-the-user-answers-correctly-without) – vinS

+0

해결책에 문제가 있다고 생각하지 않습니다. 질문을 잊어 버렸습니다. –

답변

0

나는 그것을 구조화하고,이 같은 주에 변수에 할당 방법 재 시도 할 것이다 당신의 방법에 스캐너를 통과하지 것이다 예외가 잡힌 방법 때, ID가 또한 잡을 만들기, 어쩌면 일반적인 예외를 사용하는 것이 좋습니다 (예외 예외)

main method call of method 
 
    --------------------------- 
 
     int something= getAge(); 
 
     ---------------------------------------------------------- 
 

 
     method structure like this, 
 
    --------------------------------------------- 
 

 
     public static int getAge() { 
 
      int age; 
 
    age = scanner.nextInt(); 
 
      boolean repeat = true; 
 

 
      while (repeat) { 
 
       try 
 
       { 
 
        System.out.println("Enter the soldier's age: "); 
 
        
 
        
 
     if(age<=17){ 
 
        repeat = false; 
 
     } 
 

 
    if(age>17){ 
 

 

 
    getAge(); 
 
    } 
 
       } 
 
       catch(InputMismatchException exception) 
 
       { 
 
        System.out.println("ERROR: You must enter an age of 17 or higher"); 
 
        getAge(); 
 
       } 
 

 
      } 
 
      return age; 
 
     }

<!-- end snippet --> 
+0

생각이나 의견이 있으십니까? 또한 자바 초보자, 내 솔루션에 대해 어떻게 생각하십니까? –

2

사용할 수있는 다음 입력 토큰이 정수가 아닌 경우, nextInt() 잎 그 Scanner 내부 버퍼 입력 사용되지 않은. 아이디어는 다른 Scanner 방법 (예 : nextDouble())으로 읽으려고 할 수 있다는 것입니다. 불행하게도 이것은 버퍼링 된 쓰레기를 없애기 위해 무언가를하지 않으면 nextInt()에 대한 다음 전화는 다시 같은 쓰레기를 읽으 려 시도 할 것입니다.

따라서 정크를 플러시하려면 nextInt()에 다시 전화하기 전에 next() 또는 nextLine() 중 하나를 호출해야합니다. [없이 정확하게 사용자가 응답 할 때까지 while 루프에서 한번에 캐치를 사용하려고의

try { 
    //... 
} 
catch(InputMismatchException exception) 
{ 
    System.out.println("ERROR: You must enter an age of 17 or higher"); 
    scanner.next(); // or scanner.nextLine() 
    repeat = true; 
} 
+0

이것은 허용 된 대답이어야합니다. –

+0

감사합니다! 스캐너 작동 방식에 익숙해 져 있습니다. –