'Scanner.nextLine(); not reading first name and last name

So I'm trying to get the user to input their first and last name. I tried using Scanner.next(); but that only reads the first name (the first token), but I also need the Scanner to read the last name. So I did the following:

Scanner sc = new Scanner(System.in);
Player1 player1 = new Player1();
System.out.print("Please write your first name and last name: ");
player1.setName(sc.nextLine());

So here is my code. I wanted that the scanner reads the first and the last name and passes that into the method setName which saves the input into a variable located in the Player1 class.

Now when I compile and start the program it just prints out the statement "Please write your first name and last name" but after that I can't enter nothing.

Player1 player1 = new Player1();
Player2 player2 = new Player2();
Scanner sc = new Scanner(System.in);
System.out.print("Write your first and last name: "); 
player1.setName(sc.nextLine());
System.out.print("\nWrite your first and last name: ");
player2.setName(sc.nextLine());

Now this code is pretty much the same except that I wan't the second user to input their first and last name as well. Here when I compile the program I cannot enter any information after the first statement but after that I can only input the first and the last name for the second user.

What is going on here ? I would appreciate all the help !



Solution 1:[1]

Scanner sc = new Scanner(System.in);

        System.out.print("Do you want to continue ? y/n ?");
        String yesOrNo = sc.next();


        System.out.println("Please write your first and last name");
        String name = sc.nextLine();
        System.out.println("Please write your first and last name");
        String name2 = sc.nextLine();

I fixed it a little bit but there was another peace of code above that. When I removed it everything started working fine. But what was wrong with it ?

Solution 2:[2]

I know this thread is years old, but I just ran into the same problem and couldn't find the solution on the web. However, I tried experimenting and just added a space between scanner objects. Like so...

System.out.println("Please enter your full name:");
String name = scanner.next() + " " + scanner.next();

And it registered as a first and last name. I hope this solution works for anyone else. It at least works for inputting information into an SQL database.

Solution 3:[3]

I would try assigning the result of calling sc.nextLine() to a string instead of passing it directly to a method.

String player1name = sc.nextLine(); player1.setName(player1name);

This may help you isolate your problem.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Seith09
Solution 3 Harry