扫描仪只读取第一个单词而不是行

在我当前的程序中,一种方法要求用户输入产品的描述作为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将仅产生“Sparkling”。

任何帮助将不胜感激!

nextLine()替换next() nextLine()

 String productDescription = input.nextLine(); 

使用input.nextLine(); 而不是input.next();

Scanner的javadocs回答了你的问题

扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格。

您可以通过执行类似操作来更改Scanner正在使用的默认空白模式

 Scanner s = new Scanner(); s.useDelimiter("\n"); 

input.next()接受输入字符串的第一个以whitsepace分隔的单词。 因此,通过设计,它可以完成您所描述的内容。 尝试input.nextLine()

Javadoc救援:

扫描程序使用分隔符模式将其输入分解为标记,分隔符模式默认匹配空格

nextLine可能是您应该使用的方法。