[java] Scanner only reads first word instead of line

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!

This question is related to java string java.util.scanner

The answer is


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


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");

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.


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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to java.util.scanner

How do I use a delimiter with Scanner.useDelimiter in Java? How to read multiple Integer values from a single line of input in Java? What's the difference between next() and nextLine() methods from Scanner class? Read line with Scanner Rock, Paper, Scissors Game Java Java using scanner enter key pressed Scanner is never closed how to insert a new line character in a string to PrintStream then use a scanner to re-read the file Exception in thread "main" java.util.NoSuchElementException Using a scanner to accept String input and storing in a String Array