2011-02-27 4 views
0

아래 코드의 스 니펫을 사용하여 한 번에 공백으로 구분 된 4 개의 값을 입력 할 수 있습니다.이 경우 개별적으로 캡처되어 변수에 할당됩니다. 또는 사용자는 각 값 사이의 프롬프트를 기다리는 동안 한 번에 하나의 값을 입력 할 수 있습니다. if (in.hasNext())가 내가 원하는 것처럼 작동했다면,이 솔루션은 아래 코드에서 쉽게 수행 할 수 있었지만 hasNext는 분명히 항상 TRUE로 평가됩니다. 스트림이므로 프로그램은 입력을 차단하고 대기합니다. 이 코드를 조정하여 원하는 결과를 얻을 수있는 방법이 있습니까? (년, 월, 일 나중에 프로그램에서 정수로 구문 분석 얻을 문자열입니다.) 감사합니다java hasNext 더 많은 토큰을 찾기 위해 스캐너를 검사하는 방법

Scanner in = new Scanner(System.in); 
System.out.println("Please enter your first name, last name, or full name:"); 
traveler = in.nextLine(); 

System.out.println("Please enter your weight, birth month, birth day of month, and birth year as numbers.\nYou may enter all the numbers at once -- right now -- or you may enter them one at a time as the prompts appear.\nOr, you may also enter them in any combination at any time, so long as weight (at least) is entered now and the remaining \nthree numbers are eventually entered in their correct order:"); 
pounds = in.nextInt(); 

if (in.hasNext()) { 
    month = in.next(); 
} else { 
    System.out.println("Please enter your birth month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth month:"); 
    month = in.next(); 
    } 
if (in.hasNext()) { 
    day = in.next(); 
} else { 
    System.out.println("Please enter your birth day of month, or a combination of remaining data as described previously, so long as the data you enter now begins with birth day of month:"); 
    day = in.next(); 
    } 
if (in.hasNext()) { 
    year = in.next(); 
} else { 
    System.out.println("If you've made it this far, then please just enter your birth year:"); 
    year = in.next(); 
    } 

답변

1

사용자가 입력 한 값 얼마나 많은과를 결정하는 split(" ")를 호출 한 후, 한 번에 한 줄을 읽어보십시오.

+0

감사합니다. 배열 (배열 길이 테스트)을 사용하여 split ("\\ s +")으로 전환하여 토큰을 캡처하거나 아직 입력되지 않은 토큰을 프롬프트합니다. 마지막으로 사용자 순차 입력 순열을 스플릿과 배열로 함께 넣으려면 IF ELSE를 사용해야했지만 지금은 작동합니다. 조언을 주셔서 다시 한번 감사드립니다. 스캐너가 비어 있다고 생각하게 만드는 방법을 볼 수 없었기 때문에 if (in.hasNext())를 버렸습니다. – finlander

0

차단없이 읽을 수있는 문자 수를 반환하는 InputStream.available() 메서드가 있습니다. 그러나 완전한 숫자 또는 라인이 있는지 여부는 결정하지 않습니다. Scanner 클래스의 설명서에 명시 적으로 hasNext이 차단 될 수 있다고 나와 있습니다.

관련 문제