2017-02-27 3 views
0

내가 이해하지 못하는 문제가 발생했습니다. nextLine()은 문장이어야합니다. 맞습니까?자바 | 문자열 유형

System.out.println("Enter film's name"); 
a = scan.nextLine(); 
System.out.println("What number did the film released?"); 
b = scan.nextInt(); 
System.out.println("Who's the director?"); 
c = scan.nextLine(); 
System.out.println("How long is the film in minutes?"); 
d = scan.nextInt(); 
System.out.println("Have you seen the movie? Yes/No?"); 
e = scan.next(); 
System.out.println("Mark for the film?"); 
f = scan.nextDouble(); 

이 해제 날짜까지 제대로 실행 한 다음이 함께 "얼마나 오래하면 영화"그것은 일을 가정처럼 작동하지 않습니다 "감독 누구"보여줍니다.

사용 방법 nextLine(); 그리고 왜 저에게 적합하지 않습니까?

+0

실제 문제를 설명해주십시오. –

+0

비슷한 질문에 답변되었습니다. 다음을 참조하십시오 : http://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-nextint-or-other-nextfoo – shivsky

+2

nextInt는 다음 토큰을 int 값으로 스캔합니다. 그래서 정수 입력을 할 때마다 \ n을 덧붙여 야합니다. –

답변

0

문제는 Scanner.nextInt()은 다음 행으로 읽지 않습니다. 따라서 nextLine(을 발급해야 함) 내용을 버리십시오.

public static void main(String[] args) { 
    Scanner scan = new Scanner(System.in); 
    System.out.println("Enter film's name"); 
    String a = scan.nextLine(); 
    System.out.println("What number did the film released?"); 
    int b = scan.nextInt(); 
    scan.nextLine(); // this 
    System.out.println("Who's the director?"); 
    String c = scan.nextLine(); 
    System.out.println("How long is the film in minutes?"); 
    int d = scan.nextInt(); 
    scan.nextLine(); // this 
    System.out.println("Have you seen the movie? Yes/No?"); 
    String e = scan.next(); 
    System.out.println("Mark for the film?"); 
    double f = scan.nextDouble(); 
    scan.nextLine(); // after nextDouble() too 
} 
+0

감사합니다. 해결! – KNO3

+0

그러면이 대답을 수락 하시겠습니까? –

1

버퍼가 채워지면 연속 호출 할 때마다 스캐너가 재설정됩니다. scan.reset(); . 그 이유는 이전 문자가 입력 스트림에 캐시되기 때문입니다.

+0

또한 nextInt()는 입력에서 마지막 새 라인 ASCII 문자를 사용하지 않습니다. 이 문제를 해결하려면 scan.nextLine()을 사용하여 int 값을 가져온 다음 Integer.parseInt (scan.nextLine())를 가져옵니다. 그러나 먼저 정수를 가져 와서 정수인지 확인한 다음 parseInt 변환을 수행하십시오. nextInt() 또는 next를 사용하지 마십시오. – Remario