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!
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.
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.
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.
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.
Replace next()
with nextLine()
:
String productDescription = input.nextLine();
Use input.nextLine();
instead of input.next();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With