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!
Solution 1:
Replace next()
with nextLine()
:
String productDescription = input.nextLine();
Solution 2:
Use input.nextLine();
instead of input.next();