2015-02-01 2 views
-1

사용자의 데이터를 읽는 중입니다 (시험 점수). 그런 다음 성적을 확인하고 있습니다. 그 후에 나는 성적을 표시하고있다. 그런 다음 사용자에게 다른 학년을 입력 할 것인지 묻습니다. 예라고 대답하면 다른 시험 점수를 입력하라고합니다. 그러나 여기에서는 try/catch를 사용하여 입력중인 데이터 유형의 유효성을 검사합니다. 그들이 정수가 아닌 다른 것을 입력하면 다시 루프를 시도하고 다른 등급을 입력하고 싶지만 디스플레이에 정수 오류 메시지를 입력하십시오. 그러나 여기 루프 프린트는 다른 학년을 두 번 입력하고 시험 점수를 두 번 올리면 이전 점수를 인쇄하고 다른 학년 진술을 두 번 입력하고 싶은 것을 인쇄합니다. 왜 이런 일이 발생합니까?루프가 잘못 인쇄되는 동안

import java.util.InputMismatchException; 
import java.util.Scanner; 


public class CatchingException { 

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    int score; 
    String choice; 
    boolean loop = true; 


    try { 
     System.out.println("Enter your percentage mark: "); 
     score = scan.nextInt(); 


     do { 
      if(score <40) { 
       System.out.println("You FAILED"); 
      }else if(score >=40 && score <50){ 
       System.out.println("Your grade: PASS MARK"); 
      }else if(score >=50 && score <60) { 
       System.out.println("Your grade: 2:2"); 
      }else if (score >=60 && score <70) { 
       System.out.println("Your grade: 2:1"); 
      }else { 
       System.out.println("Your grade: 1:1"); 
      } 

      System.out.println("Do you want to enter another grade: "); 
      choice = scan.next(); 
      if(choice.equalsIgnoreCase("yes")) { 
       System.out.println("Enter your percentage mark: "); 
       try{ 
        score = scan.nextInt(); 
       }catch(InputMismatchException e) { 
        System.err.println("Enter Integer"); 
        loop = false; 
       } 

      } 
     }while(!loop); 

    }catch(InputMismatchException e) { 
     System.err.println("Incorrect Input "); 
    } 

    System.out.println("program terminated"); 
    scan.close(); 

} 

    } 
+1

텍스트를 편집하십시오. 그것을 읽는 것은 거의 불가능합니다. – SklogW

+0

@Pshemo 나는 OP가 키보드 버퍼에'nextInt'에 의해 끝나는 줄을 처리한다고 믿습니다. –

+0

@ PM77-1'#nextInt()'는 공백을 신경 쓰지 않습니다. – Tom

답변

0

브랜칭 문과 레이블을 사용하여이 작업을 단순화하십시오!

import java.util.InputMismatchException; 
import java.util.Scanner; 


public class CatchingException { 

    public static void main(String[] args) { 


     Scanner scan = new Scanner(System.in); 
     int score; 
     String choice; 

     Main: 
     while (true) { //this will continue until we call "break Main;" 
      try { 
       System.out.println("Enter your percentage mark: "); 
       score = scan.nextInt(); 

       if (score < 40) { 
        System.out.println("You FAILED"); 
       } else if (score >= 40 && score < 50) { 
        System.out.println("Your grade: PASS MARK"); 
       } else if (score >= 50 && score < 60) { 
        System.out.println("Your grade: 2:2"); 
       } else if (score >= 60 && score < 70) { 
        System.out.println("Your grade: 2:1"); 
       } else { 
        System.out.println("Your grade: 1:1"); 
       } 

       Prompt: 
       while (true) { //this will continue until we call "break Prompt;" 
        System.out.println("Do you want to enter another grade: "); 
        choice = scan.next(); 
        try { 
         if (choice.equalsIgnoreCase("yes")) { 
          continue Main; //OK. Start again at "Main:" 
         } else if (choice.equalsIgnoreCase("no")) 
          break Main; //OK. We're done. 
         else { 
          System.err.println("Incorrect Input "); 
          continue Prompt; //whoops! try asking again. 
         } 
        } catch (InputMismatchException e) { 
         System.err.println("Incorrect Input "); 
         continue Prompt; //whoops! try asking again. 
        } 
       } 
      } catch (InputMismatchException e) { 
       System.err.println("Incorrect Input "); 
       continue Main; //whoops! try another input. 
      } 
     } 
     System.out.println("program terminated"); 
     scan.close(); 
    } 
} 
0

는 우선, 방법 당신이 loop 변수를 설정하는 당신이 한 looptrue 그대로 반복하는 유지하려는 것을 나타냅니다. 이 경우 while(!loop);while (loop);

으로 변경해야합니다. 그런 다음 새로운 등급을 입력할지 묻는 메시지가 표시 될 때 사용자가 "아니오"라고 쓰면 어떻게 될지 살펴야합니다. 위와 같은 변경 사항이 적용되므로 계속 반복 할 것입니다. 이 문제를 해결하려면, 당신은 ("없음"이외의) 모든 입력의 원인이 반복하는 유지하는 루프를 만들 것입니다

System.out.println("Do you want to enter another grade: "); 
choice = scan.next(); 
if(choice.equalsIgnoreCase("no")) { 
    loop = false; 
} 

이 같은 것으로

System.out.println("Do you want to enter another grade: "); 
choice = scan.next(); 
if(choice.equalsIgnoreCase("yes")) { 
    System.out.println("Enter your percentage mark: "); 
    try{ 
     score = scan.nextInt(); 
    }catch(InputMismatchException e) { 
     System.err.println("Enter Integer"); 
     loop = false; 
    } 
} 

을 변경할 수 있습니다. 물론

, 당신을 필요로 이렇게 내부

System.out.println("Enter your percentage mark: "); 
score = scan.nextInt(); 

를 넣어 (당신은 단지 "는 예는"일을, 다음 몇 가지 추가 검사로 해결하기 위해. 아주 쉽게해야합니다) do-while 루프. 당신은 사용자가 올바른 정수를 입력하지 않는 경우 퍼센트 점수를 요구 유지하려면

do { 
    System.out.println("Enter your percentage mark: "); 
    score = scan.nextInt(); 

, 당신은 같은 것을 할 수 있습니다

System.out.println("Enter your percentage mark: "); 
while (!scan.hasNextInt()) { 
    System.out.println("Please enter a valid percentage mark: "); 
    scan.next(); 
} 
score = scan.nextInt(); 

이렇게까지 묻는 유지합니다 사용자가 실제 정수를 입력합니다. 귀하의 질문이기 때문에

+0

기본적으로 프로그램의 요점은 프로그램이 물어볼 때 백분율 표시를 입력하고 사용자가 정수 이외의 다른 값을 입력하면 프로그램이 반복되어야하고 여기서 다시 백분율 표시를 입력하십시오. 여기서는 프로그램이 무한 루프로 바뀝니다 –

+0

당신이 무슨 뜻인지 확실하지. 코드를 변경하면 잘못된 입력에 대해 다시 묻지 않습니다. 그러나 코드를 실행하고 비 정수를 입력하면 "_Invalid Input_"이 인쇄되고 종료됩니다. 무한 루프가 없습니다. – MAV

0

why is this happening 나는 당신에게 그것을 설명하려고합니다. 여기

catch(InputMismatchException e) { 
    System.err.println("Enter Integer"); 
    loop = false; 
} 

프로그램이 에러 메시지를 출력 :

Enter your percentage mark: 
70 
Your grade: 1:1 
Do you want to enter another grade: 
yes 
Enter your percentage mark: 
a 

a가 유효한 정수 없기 때문에 Scanner#nextInt()InputMismatchException 프로그램이 catch 블록으로 "이동"슬로우, 다음과 같이 내 예시 입력된다 loopfalse으로 설정합니다. while 조건 while(!loop)으로 인해 새로운 루프 반복을 수행하려고합니다.Scanner#nextInt()은 입력 스트림에서 유효하지 않은 입력을 "읽지"않고 제거하기 때문에 여전히 존재합니다.

그래서 우리는 다시 여기에 있습니다 : 당신이 알다시피

do { 
    if(score <40) { 
     System.out.println("You FAILED"); 
    } 
    //... 

따라서, 프로그램은 이전의 점수를 입력 70을 재사용, 여기에는 score = scan.nextInt(); 문이 없습니다.

System.out.println("Do you want to enter another grade: "); 
choice = scan.next(); 
: 우리는 다른 점수를 입력 싶은 경우는, 우리를 다시 요청합니다

Enter your percentage mark: 
70 
Your grade: 1:1 
Do you want to enter another grade: 
yes 
Enter your percentage mark: 
a 
Enter Integer 
Your grade: 1:1 

점수 확인 후 : 때문에 그 사실에, 그것은 (이 점에 대한 전체 출력까지) 다시 같은 점수 메시지를 인쇄

여기 또 다른 문제가 있습니다. 마지막 반복에서 입력 한 a을 계속 사용할 수 있으며 Scanner#next()이이 입력을 허용하므로 choice은 이제 "a"이됩니다. 이 if 문은 false를 반환하고 몸이 생략됩니다 왜 ("a""yes" 같지 않은) :

if(choice.equalsIgnoreCase("yes")) { 

우리의 상황이 a이 입력 스트림에서 사라지고 loop은 아직 설정되어 있는지, 지금 false. 따라서, 프로그램은 또 다른 루프 반복을하고 우리는 (다시) 루프의 시작 부분에 있습니다

do { 
    if(score <40) { 
     System.out.println("You FAILED"); 
    } 
    //... 

을 그리고 다시, 우리는 지금 여기에 평가 점수 읽기 아닙니다. 대신 우리는 점수 70의 이전 입력을 재사용하고 있습니다.

Your grade: 1:1 

좋은 점은 다음과 같습니다 : a는 입력 스트림에서 사라지고 다음 질문은 사용자로부터 사실 요청에서 새로운 입력을 수행합니다

System.out.println("Do you want to enter another grade: "); 
choice = scan.next(); 
그 말은, 우리는 동일한 메시지가

그가 원하는 것을 결정하는 것은 그에게 달려 있습니다.


은 이제 볼 수 있습니다, 당신은 당신의 catch 블록에서 유효하지 않은 입력을 읽을 필요하거나 나중에 당신을 귀찮게합니다. do/while 루프 시작 부분에 새로운 score을 읽어야합니다. 그렇지 않으면 이전 입력을 다시 사용할 수 있습니다.

답변을 통해 프로그램을 조금 더 이해하는 데 도움이되기를 바랍니다. :). 그리고 디버거를 사용하는 방법을 배우려면 시간이 필요합니다. 이런 경우에는 매우 도움이됩니다.

0

솔직히 여기 do-while 루프를 할 이유가 없었습니다.

1)이 코드를 쉽게
2)

내가 가진 쉽게 프로세스를 만듭니다 읽기 :이 루프을 사용하여 설명 할 숙제 운동과 같은 경우를 제외하고는 하나, 당신은 정말에만 사용해야합니다 코드를 직접 읽는 데 문제가 있습니다. 나는 단지 이것을했고 그것은 잘 작동합니다. 참고 : 사용자가 yes 또는 no를 입력하지 않은 경우뿐만 아니라 수행 방법을 알아야 할 경우이를 위해 어떤 시도 잡기도 추가하지 않았습니다. 그냥 기본적인 예입니다.

public static void main(String[] args) 
{ 
    Scanner scan = new Scanner(System.in); 
    int score; 
    String choice; 
    while(true) 
    { 
     System.out.println("Enter your percentage mark: "); 
     score = scan.nextInt(); 
     if(score <40) 
     { 
      System.out.println("You FAILED"); 
     } 
     else if(score >=40 && score <50) 
     { 
      System.out.println("Your grade: PASS MARK"); 
     } 
     else if(score >=50 && score <60) 
     { 
      System.out.println("Your grade: 2:2"); 
     } 
     else if (score >=60 && score <70) 
     { 
      System.out.println("Your grade: 2:1"); 
     } 
     else 
     { 
      System.out.println("Your grade: 1:1"); 
     } 

     System.out.println("Do you want to enter another grade: "); 
     choice = scan.next(); 

     if(choice.equalsIgnoreCase("no")) 
     { 
      System.out.println("Program terminated"); 
      scan.close(); 
      break; 
     } 
    } 
} 
관련 문제