Scanner only reads first word instead of line

半腔热情 提交于 2019-11-30 08:00:50

问题


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!


回答1:


Replace next() with nextLine():

String productDescription = input.nextLine();



回答2:


Use input.nextLine(); instead of input.next();




回答3:


The javadocs for Scanner answer your question

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You might change the default whitespace pattern the Scanner is using by doing something like

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



回答4:


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().




回答5:


Javadoc to the rescue :

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

nextLine is probably the method you should use.



来源:https://stackoverflow.com/questions/7946664/scanner-only-reads-first-word-instead-of-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!