illustriouscake
illustriouscake

Reputation: 37

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.

Upvotes: 0

Views: 266

Answers (1)

user8635668
user8635668

Reputation: 31

We can simplify (and fix) the code somewhat before getting to the crux of the issue to the following:

public void addPlayers(Scanner scanner) {
    this.players = new ArrayList<Player>();

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

For issues regarding the scanner input seemingly being skipped initially, that suggests to me that it already has some input (an empty line, here) to process before you've entered the function, and hence doesn't need to wait for your input. It seems like you'd be better off just declaring the Scanner inside the method instead of taking it as a parameter. Otherwise, there are many other questions dealing with this issue. You could continue attempting to read lines until the String received is has a positive length, for example.

Upvotes: 2

Related Questions