vendredi 21 février 2020

Creating an array of random elements from a separate array, up to a given length (Java)

I'm working on a GameBuilder class that builds a Game object using a player count, array of player names, game board width/height, and a couple more irrelevant params. I'd like to allow a Game to be setup without specifying names. I have an array of default names I'd like to pick from if this is the case.

I have two constructors. The main one receives a player count, and an array of player names (see below).

public GameBuilder withPlayers(final Integer players, final String[] someNames) {
    if ((players >= MINIMUM_NUMBER_OF_PLAYERS) && (players <= MAXIMUM_NUMBER_OF_PLAYERS)) {
      if (someNames.length == players) {
        tempPlayers = players;
        names = someNames;
        return this;
      } else {
        throw new IllegalArgumentException("Player/Name mismatch!");
      }

    } else {
      throw new IllegalArgumentException("The number of players must be between " + MINIMUM_NUMBER_OF_PLAYERS + " and " + MAXIMUM_NUMBER_OF_PLAYERS + ".");
    }

(tempPlayers and names are declared elsewhere and eventually given to the Game constructor).

My second constructor takes only one parameter, player count, and chains onto the main constructor above. This is where I'd like to create an array of randomly picked names (from the default names array) up to the size of the specified player count, to then pass on to the main constructor, which will in turn, get passed to the Game object.

Is this possible? I'm still relatively new to Java so any advice would be greatly appreciated.

Thanks




Aucun commentaire:

Enregistrer un commentaire