扫描仪仅读取第一个单词而不是行
在我当前的程序中,一种方法要求用户以 String
输入形式输入产品描述。但是,当我稍后尝试打印此信息时,仅显示 String
的第一个单词。这可能是什么原因造成的?我的方法如下:
void setDescription(Product aProduct) {
Scanner input = new Scanner(System.in);
System.out.print("Describe the product: ");
String productDescription = input.next();
aProduct.description = productDescription;
}
因此,如果用户输入是“橙味起泡苏打水”,则 System.out.print 只会产生“起泡”。
任何帮助将不胜感激!
In my current program one method asks the user to enter the description of a product as a String
input. However, when I later attempt to print out this information, only the first word of the String
shows. What could be the cause of this? My method is as follows:
void setDescription(Product aProduct) {
Scanner input = new Scanner(System.in);
System.out.print("Describe the product: ");
String productDescription = input.next();
aProduct.description = productDescription;
}
So if the user input is "Sparkling soda with orange flavor", the System.out.print
will only yield "Sparkling".
Any help will be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
替换
next()
与nextLine()
:Replace
next()
withnextLine()
:使用
input.nextLine();
而不是input.next();
Use
input.nextLine();
instead ofinput.next();
Scanner 的 javadocs 回答了您的问题
您可以通过执行类似的操作来更改扫描仪使用的默认空白模式
The javadocs for Scanner answer your question
You might change the default whitespace pattern the Scanner is using by doing something like
input.next() 接受输入字符串的第一个空格分隔的单词。因此,根据设计,它会执行您所描述的操作。尝试
input.nextLine()
。input.next() takes in the first whitsepace-delimited word of the input string. So by design it does what you've described. Try
input.nextLine()
.Javadoc 来救援:
nextLine
可能是您应该使用的方法。Javadoc to the rescue :
nextLine
is probably the method you should use.您在此线程中看到了两种解决方案:
nextLine()
和useDelimiter
,但是第一个解决方案仅在您只有一个输入时才有效。以下是使用它们的完整步骤。使用
nextLine()
正如 @rzwitserloot 提到的,如果
.next()
子例程在nextLine()
调用之前,这将会失败。要解决此问题,请在顶部定义.nextLine()
子例程以忽略空白字符。使用 useDelimiter()
可以将 Scanner 类的默认空白分隔符更改为换行符。
There are two solutions as you've seen in this thread:
nextLine()
anduseDelimiter
, however the first one will only work when you have just one input. Here are the complete steps to use both of them.Using
nextLine()
As @rzwitserloot mentioned, this will fail if a
.next()
subroutine precedes thenextLine()
call. To fix this, define the.nextLine()
subroutine at the top to ignore the white-space character.Using
useDelimiter()
You can change the default whitespace delimiter of the Scanner class to a newline character.