Scanner only reads first word instead of line

Kristian picture Kristian · Oct 30, 2011 · Viewed 166.3k times · Source

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!

Answer

Tim Cooper picture Tim Cooper · Oct 30, 2011

Replace next() with nextLine():

String productDescription = input.nextLine();