37

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);
}
Jason C
  • 34,234
  • 12
  • 103
  • 151
igeer12
  • 391
  • 1
  • 4
  • 8

6 Answers6

60

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

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

Sailesh Kotha
  • 1,324
  • 1
  • 16
  • 27
Prabhakaran Ramaswamy
  • 23,910
  • 10
  • 51
  • 62
  • Thanks for the really fast response, really helped. – igeer12 Oct 22 '13 at 05:32
  • 4
    I'm having this same issue but the String I'm using nextLine() for ends up being empty. This is what my code looks like: `System.out.print("License plate: "); String license = sc.nextLine();`. Did the Scanner change after this answer was posted? – Alex Dueppen Sep 13 '17 at 03:40
  • Hi Alex, please find my answer here, see if it helps - https://stackoverflow.com/a/64991271/5345105 – Shubham Arya Nov 25 '20 at 05:28
16

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.

Woody
  • 850
  • 6
  • 16
  • next() can read the input only till the **whitespace**. It can't read two words separated by a **whitespace**. **whitespace** includes space, tab and linefeed – Fred Hu Sep 13 '20 at 16:50
3

From Scanner documentation:

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

and

public String next()

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

This means by default the delimiter pattern is "whitespace". This splits your text at the space. Use nextLine() to get the whole line.

PurkkaKoodari
  • 6,383
  • 5
  • 33
  • 54
3
 public static void processName(Scanner scanner) {
        System.out.print("Please enter your full name: ");
        scanner.nextLine();
        String name = scanner.nextLine();
        System.out.print(name);
    }

Try the above code Scanner should be able to read space and move to the next reference of the String

2

scanner.next(); takes only the next word. scanner.nextLine(); should work. Hope this helps

Wold
  • 923
  • 1
  • 11
  • 25
1

try using this

String name = scanner.nextLine();
Ankur
  • 120
  • 2