I am writing a program that asks for the person's full name and then takes that input and reverses it (i.e John Doe - Doe, John). I started by trying to just get the input, but it is only getting the first name.
Here is my code:
public static void processName(Scanner scanner) { System.out.print("Please enter your full name: "); String name = scanner.next(); System.out.print(name); }
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
Basic Usage. The hasNext() method checks if the Scanner has another token in its input. A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default. That is, hasNext() checks the input and returns true if it has another non-whitespace character.
This happens because when the nextInt() method of the Scanner class reads the roll number, it returns the value 1 . This value is stored in the variable number. Therefore, when we use the nextLine() method to read the name, it starts reading the input from the cursor's current position.
nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
Change to String name = scanner.nextLine();
instead of String name = scanner.next();
See more on documentation here - next() and nextLine()
Try replacing your code
String name = scanner.nextLine();
instead
String name = scanner.next();
next()
can read the input only till the space
. It can't read two words separated by space
. Also, next()
places the cursor in the same line after reading the input.
nextLine()
reads input including space
between the words (that is, it reads till the end of line \n
). Once the input is read, nextLine()
positions the cursor in the next line.
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