Constructor chaining and preparing arguments before calling this(aguments)

I am making a Yahtzee game. I want to supply a constructor for different cases. Suppose you couldn't be bothered to supply the names of the players that you want to create a new game with, I'd like to just create "Unnamed Player 1", "Unnamed Player 2", etc.

Here is how I am trying to do that:

public class YahtzeeGame {
    private List<Player> players = new ArrayList<>();

    public YahtzeeGame(String[] playerNames) {
        for (String playerName : playerNames) {
            players.add(new Player(playerName));
        }
    }

    public YahtzeeGame(int numberOfPlayers) {
        String[] playerNames = new String[numberOfPlayers];
        for (int i = 0; i < numberOfPlayers; i++) {
            playerNames[i] = "Unnamed player " + (i+1);
        }
        this(playerNames); // ERROR: "Constructor call must be the first statement in a constructor.
    }

    public YahtzeeGame(String playerName) {
        this(new String[] {playerName});
    }

    public YahtzeeGame() {
        this("Unnamed player");
    }
}

This doesn't work of course, as per the error written in the comment.

Is there a way around this? Do I need a factory pattern for this?

Jon Skeet
people
quotationmark

Yes, there's fairly simple way around it, at least in this case: create a static method which will prepare the constructor argument for you. Call that from the this expression:

public YahtzeeGame(int numberOfPlayers) {
    this(getUnnamedPlayers(numberOfPlayers));
}

private static String[] getUnnamedPlayers(int numberOfPlayers) {
    String[] playerNames = new String[numberOfPlayers];
    for (int i = 0; i < numberOfPlayers; i++) {
        playerNames[i] = "Unnamed player " + (i+1);
    }
    return playerNames;
}

Note that it does have to be static, because you can't call any instance methods on this before the chained constructor, either.

people

See more on this question at Stackoverflow