2012-10-25 2 views
3

사용자 입력을 0에서 100 사이의 int로 얻으려고 시도하고 입력이이 기준과 일치하지 않는 한 "다시 시도"하라는 메시지를 표시합니다.사용자에게 0과 100 사이의 숫자를 물어볼 수 있습니까?

내 코드는 지금까지 내 목표 달성에 어느 정도 성공 : 당신이 볼 수 있듯이

import java.util.Scanner; 

public class FinalTestGrade 
{ 
    public static void main(String[] args) 
    { 
     Scanner studentInput = new Scanner (System.in); 
     int testGrade; 

     System.out.println("Please enter your test grade (0 to 100)"); 
     while (!studentInput.hasNextInt()) 
      { 
      System.out.println("Your input does not match the criteria, please enter a number between 0 and 100"); 
      studentInput.next(); 
      } 
     testGrade = studentInput.nextInt(); 

     while (testGrade > 100 || testGrade < 0) 
      { 
      System.out.println("Your input does not match the criteria, please enter a number between 0 and 100"); 
      testGrade = studentInput.nextInt(); 
      } 

, 프로그램은 입력이 int로 있는지 확인합니다. 사용자가 성공적으로 int를 입력하면 프로그램은 입력 값이 0에서 100 사이인지 확인합니다. 사용자가 두 번째 프롬프트에서 이라는 응답이 아닌 int를 입력하면 (두 번째 while 루프에서 시작됨) 문제가 발생합니다. 아래의 예는 다음과 같습니다 내 동안을 결합 할 수있는 방법이 있는지

run: 
Please enter your test grade (0 to 100) 
P 
Your input does not match the criteria, please enter a number between 0 and 100 
109 
Your input does not match the criteria, please enter a number between 0 and 100 
P 
    Exception in thread "main" java.util.InputMismatchException 
      at java.util.Scanner.throwFor(Scanner.java:840) 
      at java.util.Scanner.next(Scanner.java:1461) 
      at java.util.Scanner.nextInt(Scanner.java:2091) 
      at java.util.Scanner.nextInt(Scanner.java:2050) 
      at finaltestgrade.FinalTestGrade.main(FinalTestGrade.java:24) 
Java Result: 1 
BUILD SUCCESSFUL (total time: 9 seconds) 

너무 오래 짧은 이야기, 내가 궁금하네요 그래서 그 입력 & 받아 변수로 저장 0에서 100까지의 int로 표현 루프. 이 기준에 맞지 않는 모든 입력은 입력이이 기준을 충족 할 때까지 반복되는 프롬프트를 트리거해야합니다. 어떤 제안?

답변

0
int testGrade = -1 ; 
Scanner studentInput = new Scanner(System.in); 
while (testGrade > 100 || testGrade < 0) 
{ 
    System.out.println("Your input does not match the criteria, please enter a number between 0 and 100"); 

    while(!studentInput.hasNextInt()) 
    { 
     studentInput.next() ; 
    } 
    testGrade = studentInput.nextInt(); 
} 

스트림에 유효하지 않은 문자가 있는지 확인하는 무한 루프가 있는지 확인하십시오. 그렇다면, 그것을 소비하십시오, 그것은 hasNextInt()을위한 것입니다. 유효한 항목을 입력하면 해당 루프가 종료됩니다.

+0

매우 우아한 해결책이지만, 무한 루프가 발생합니다. 입력이 조건과 일치하지 않습니다. 0 ~ 100 사이의 숫자를 입력하십시오. 입력이 잘못되었습니다! 입력 한 내용이 기준과 일치하지 않습니다. 0 ~ 100 사이의 숫자를 입력하십시오. 잘못된 입력을 입력했습니다! 등 기타 제안 사항은 무엇입니까? –

+0

mmn 시도해 보겠습니다. –

+0

@ user1775753 수정 됨. 어떻게 진행되는지 알려주세요. –

관련 문제