Using a for-loop in java to capture player names is outputting wrong number and skipping first player

I'm creating a game in java. I have written separate a method for capturing the number of players who are playing (which is working), and with the below method I am trying to capture their names, print it out to screen, and put them in an ArrayList.

public void addPlayers(Scanner scanner) {
        this.players = new ArrayList<Player>();
        int playerNumber = 1;
        String playerName = null;

        for (int loop = 0; loop <= getNumberOfPlayers(); loop++) {
            System.out.println("Player number " + playerNumber++ + ", please type your name");
            playerName = scanner.nextLine();
            System.out.println("your name is: " + playerName);
        }
    }

There are four players playing and this is the figure coming back when I output to screen System.out.println(this.numberOfPlayers), so I know getNumberOfPlayers() is correct.

This is the output I am getting though for my addPlayers method:

Player number 1, please type your name
your name is: 
Player number 2, please type your name
john
your name is: john
Player number 3, please type your name
sally
your name is: sally
Player number 4, please type your name
fred
your name is: fred
Player number 5, please type your name
eric
your name is: eric

My current code is skipping player 1 from being able to input their name and is outputting 5 players from the loop.

What I want to happen:

Player number 1, please type your name
fred
your name is: fred
Player number 2, please type your name
john
your name is: john
Player number 3, please type your name
sally
your name is: sally
Player number 4, please type your name
mary
your name is: mary

Any help would be appreciated.



Read more here: https://stackoverflow.com/questions/67008231/using-a-for-loop-in-java-to-capture-player-names-is-outputting-wrong-number-and

Content Attribution

This content was originally published by illustriouscake at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: