Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 499
Kristian Avatar asked Oct 30 '11 17:10

Kristian


People also ask

How do you go to the next line in a Scanner?

The nextLine() method of java. util. Scanner class advances this scanner past the current line and returns the input that was skipped. This function prints the rest of the current line, leaving out the line separator at the end.

Why is Scanner skipping next line?

That's because the Scanner. nextInt method does not read the newline character in your input created by hitting "Enter," and so the call to Scanner. nextLine returns after reading that newline. You will encounter the similar behaviour when you use Scanner.

How do you read a full line of a string in Java?

Java nextLine() method The nextLine() method of Scanner class is used to take a string from the user. It is defined in java.util.Scanner class. The nextLine() method reads the text until the end of the line. After reading the line, it throws the cursor to the next line.

Can a Scanner read from a string?

Scanner is simple text scanner which can parse primitive types and strings using regular expressions. So, passing System.in to Scanner allows us to parse or read string from standard input stream, which is console.


2 Answers

Replace next() with nextLine():

String productDescription = input.nextLine();
like image 110
Tim Cooper Avatar answered Oct 16 '22 01:10

Tim Cooper


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

like image 45
Eng.Fouad Avatar answered Oct 16 '22 01:10

Eng.Fouad