简体   繁体   English

扫描仪输入字符串无空格?

[英]Scanner input string without spaces?

I was wondering how I can do this. 我想知道如何做到这一点。

I was told to use kb.nextLine() instead of kb.next() , but that just results in the input being skipped when I run the program. 有人告诉我使用kb.nextLine()而不是kb.next() ,但这只会导致我在运行程序时跳过输入。

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

I was then told to do this to fix it: 然后,我被告知要解决此问题:

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

but I get an error: String cannot be resolved into a variable" "Syntax error on token "address" 但出现错误: String cannot be resolved into a variable" "Syntax error on token "address"

Your second example is wrong. 您的第二个示例是错误的。 Your first example looks okay. 您的第一个示例看起来还可以。 But not great. 但不是很好。 I assume you've been using something like nextInt() or nextDouble() . 我假设您一直在使用诸如nextInt()nextDouble() They leave a trailing new line, so you need to consume it. 它们留下了尾随的新行,因此您需要使用它。

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

If you don't need a local copy of address, 如果您不需要本地地址副本,

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

As Scanner.nextLine() Javadoc says, 正如Scanner.nextLine() Javadoc所说,

Advances this scanner past the current line and returns the input that was skipped. 使该扫描仪前进到当前行之外,并返回被跳过的输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM