2014-11-02 57 views
1

我想知道我该如何做到这一点。扫描仪输入字符串没有空格?

我被告知要使用kb.nextLine()而不是kb.next(),但这只是导致输入在我运行程序时被跳过。

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 2014-11-02 06:39:24

回答

5

你的第二个例子是错误的。你的第一个例子看起来没问题。但不是很好。我假设你一直在使用类似nextInt()nextDouble()。他们留下一条尾随的新线,所以你需要消耗它。

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

如果您不需要地址的本地副本,

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

由于Scanner.nextLine() Javadoc中说,

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