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);
}

Solution 1:

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

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

Solution 2:

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.

Solution 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.

Solution 4:

 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