0

I am writing a code that asks for user input on the names of the players and stores them in array. To do this I am using a for loop, which i thought would be more efficient, however, the code seems to do something unexpected, and I cannot see why it is doing what it does. Below is the code and the result:

Scanner reader = new Scanner (System.in);
System.out.print("Please enter the number of players:");
int players = reader.nextInt();

String[] player_name = new String[players+1];//Array to store player names
for (int i = 0; i < players; i++)//Loop to ask players their name
{
    System.out.print("Player " + (i+1) + " please enter your name:\n");//Asks player names one by one
    player_name[i] = reader.nextLine();//Saves the player names to the array
}

And here is the result when the number of players is 2:

Please enter the number of players:2

Player 1 please enter your name:

Player 2 please enter your name:

wa

BUILD SUCCESSFUL (total time: 23 seconds)

When I hit enter after typing the "name" wa to type player 2's name the program just ends.

Community
  • 1
  • 1
Benny
  • 35
  • 8

1 Answers1

1

The nextInt() doesn't grab the end of line character, AKA the "enter" after the number is entered. Instead you can use nextLine() and get the entire line and then parse it into an Integer like so

int players = Integer.parseInt(reader.nextLine());
RAZ_Muh_Taz
  • 3,964
  • 1
  • 10
  • 22
  • Oh I see, that worked, thanks, but why does it work – Benny Apr 06 '18 at 19:40
  • your welcome! feel free to mark as answer so it closes your question – RAZ_Muh_Taz Apr 06 '18 at 19:42
  • But why does this line work and mine one doesn't @RAZ_Muh_Taz – Benny Apr 06 '18 at 19:54
  • because when you call nextLine() it grabs everything typed by the user until the end of line character "enter". When you use just nextInt(), it only grabs the number and not the "enter", leaving it for the first call to nextLine() in your for loop to grab it. but because it's only the "enter" your player's name becomes "" @Benny – RAZ_Muh_Taz Apr 06 '18 at 21:11
  • I see, that makes sense – Benny Apr 07 '18 at 09:30