Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scanner doesn't see after space

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); } 
like image 677
igeer12 Avatar asked Oct 22 '13 05:10

igeer12


People also ask

Does Scanner ignore whitespace?

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Does Scanner next read 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.

Why does my Scanner nextLine skip?

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.

How do I get my Scanner to read the next line?

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.


2 Answers

Change to String name = scanner.nextLine(); instead of String name = scanner.next();

See more on documentation here - next() and nextLine()

like image 169
Prabhakaran Ramaswamy Avatar answered Sep 24 '22 14:09

Prabhakaran Ramaswamy


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.

like image 43
Woody Avatar answered Sep 23 '22 14:09

Woody