2017-11-26 4 views
0
public class MetricConversion { 
public static Scanner input = new Scanner(System.in); 
public static void main(String[] args) { 
    String masses = "null"; 
    String volumes = "null"; 
    String temps = "null"; 
    String lengths = "null"; 
    int answer1 = 0; 

    String[] options = {"Mass = 1","Temperature = 2","Length = 3","Volume = 4"}; 
    System.out.println("What would you like to convert?"); 
    for(int i = 0;i<options.length;i++) 
     System.out.println(options[i]); 

    while(!input.hasNextInt() || input.nextInt() > options.length) 
    { 
     String garbage = input.nextLine(); 
     System.out.println("That input is not valid, try again"); 
    } 
    answer1 = input.nextInt(); 
    input.nextLine(); 

값 오전 데 문제가 예를 들어 잘못된 입력을 입력하면 오류 메시지가 올바르게 인쇄되지만 올바른 입력을 입력 할 때는 루프를 중단하기 위해 두 번 입력해야합니다. 그러나 while 루프를 || 그것은 단지 가정 한 것과 같은 하나의 가치를 취합니다.사용 || 들어</p> <pre><code>answer1 = input.nextInt(); </code></pre> <p>을 위해</p> <pre><code>while(!input.hasNextInt() || input.nextInt() > options.length) </code></pre> <p>2 개 유효한 입력 대신 1 중임을 루프가 너무 많은 입력을 만드는 반면에

+1

당신의 문'input.nextInt()가'조건부 문에 사용자 입력을 취하고이 같은 루프 조건 내에서 할당 할 수 있습니다 . –

+0

do-while 루프로 while 루프를 변경하고 do-while 블록 내에서 필요한 조건을 만들어야합니다. – Ele

+0

'nextInt() <= options.length' 인 경우 조건부에서 이미 소비했습니다 (그리고 버려졌습니다). 그 값을 어딘가에 저장해야합니다. –

답변

2

변수에 값을 할당하지 않고 값을 소비하고 있습니다.

while(!input.hasNextInt() || (answer1 = input.nextInt()) > options.length) 
+0

나는 에 코드를 변경'동안 (input.hasNextInt() || (증거 = input.nextInt())> options.length!) \t \t { \t \t \t 문자열 쓰레기 = input.nextLine(); \t \t \t System.out.println ("해당 입력이 유효하지 않습니다. 다시 시도하십시오."); \t \t} \t \t ANSWER1 = input.nextInt(); ' 아직 제가 놓친 게 있는지 확실하지 않습니다, 루프를 종료하려면이 개 값을 입력합니다 그러나. –

+0

나는'증거 '가 무엇인지 모른다. 'answer1'을 의미한다면, 루프 후에 할당을 반복 할 필요가 없습니다. – shmosel

+0

오, 그래, 이해해, 고마워! –

0

당신은 while 루프에서 스캐너 인수를 소모 :

while(!input.hasNextInt()){ 
    int argument = input.nextInt(); 
    if(argument > options.length){ 
     System.out.println("That input is not valid, try again"); 
     continue; // get back to the start 
    } 
    // correctly handle your argument 
} 
관련 문제