2014-11-02 2 views
1

나는 이것을 어떻게 할 수 있는지 궁금했다.스캐너 입력 문자열에 공백이 없습니까?

나는 kb.next() 대신 kb.nextLine()을 사용한다고 들었지만 프로그램을 실행할 때 입력이 건너 뛰게됩니다.

String address; 
student.setAddress(address = kb.nextLine()); 

나는 다음이 그것을 해결하기 위해 할 말을 들었다 :

student.SetAddress(String address = kb.nextLine()); 

하지만 오류가 발생합니다 : String cannot be resolved into a variable" "Syntax error on token "address"

+3

당신이 코드의 더 많은 것을 보여줄 수 있습니까? 게시 한 첫 번째 줄은 작동해야하지만 문맥이 없으면 문제가 어디인지 말할 수 없습니다. – Eran

답변

5

두 번째 예는 잘못된 것입니다. 귀하의 첫 번째 예제는 괜찮아 보입니다. 그러나 위대하지 않아. nextInt() 또는 nextDouble()과 같은 것을 사용하고 있다고 가정합니다. 그들은 후행 줄을 남겨서 소비해야합니다. 자바 독 말한다

kb.nextLine(); // <-- consume empty trailing line. 
student.setAddress(kb.nextLine()); //<-- reads line. 

Scanner.nextLine()으로

kb.nextLine(); // <-- consume empty trailing line. 
String address; 
student.setAddress(address = kb.nextLine()); //<-- reads line. 

당신은 주소의 로컬 복사본이 필요하지 않은 경우,

Advances this scanner past the current line and returns the input that was skipped.

관련 문제