I have an array of Player objects. The players have names and when i add a player, i want to check if the playername already exists. Following code never throws the exception, it just adds duplicate players.
public void addPlayer(String name, boolean gender, int index) throws RuntimeException {
List<String> names = new ArrayList<>();
if (names.contains(name))
throw new DuplicatePlayerException();
else {
players[index] = new Player(name, gender);
names.add(name);
}
}
List<String> nameswhich is empty. It should be aclass-level-variablebooleanfor gender is somehow from the last century...namescannot contain the given name in the method because it will always be empty before yourifstatement that checks if the name is contained. Make it a class attribute...