0

I'm trying to create a basic "addPlayer" method for a game. The method should add a "Player" to the array of players.

Current code:

  @Override
  public void addNewPlayer(String name) {
  Player one = new Player(name);
  players.add(one);
  }

The problem I have is that this can only create one Player, as the creation of the second will cause the second player to be associated with the name "one".

Ideally I'd like to make the name of the Player object dependant on the parameter "name" passed in. Is this possible?

I'm using Player objects to have a name and int final identification for the game. Maybe I need to rethink that design?

1
  • 1
    The name of the Player variable doesn't matter, you should just call that player. Everytime you need to add a new player, you invoke addNewPlayer. So the caller is the one that'll be doing the multiple calls to this method. Commented Oct 22, 2015 at 4:14

1 Answer 1

2

You are confused. In your example one is only visible in the method scope, when the method ends that reference variable is no-longer reachable. You could change

public void addNewPlayer(String name) {
  Player one = new Player(name);
  players.add(one);
}

to

public void addNewPlayer(String name) {
  players.add(new Player(name));
}

Note that this is functionally identical to your version. players (assuming it's a Collection), can contain multiple Player instances.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick response and the clarification! I was clearly confused and searching didn't help solve the question as it ended up being a non-issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.