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);
}
}
3 Answers 3
public void addPlayer(String name, boolean gender, int index) throws RuntimeException {
List<String> names = new ArrayList<>(); // you create a new instance of the list each time you call it, so it'll always be empty
if (names.contains(name)) // your empty list does not contain anything
throw new DuplicatePlayerException();
else {
players[index] = new Player(name, gender);
names.add(name);
}
}
You'll need to change your method, to work with an instance level list:
private List<String> names = new ArrayList<>();
public void addPlayer(String name, boolean gender, int index) throws RuntimeException {
if (names.contains(name))
throw new DuplicatePlayerException();
else {
players[index] = new Player(name, gender);
names.add(name);
}
}
so the contents of names
won't be erased each time you call your method.
Comments
You could consider Set<Player>
instead of array. Set
by definition can not contain the duplicates. Assuming Player
has implemented equals/hashcode
your code might look like:
Set<Player> players = new HashSet<>();
public void addPlayer(Player player) throws RuntimeException {
if (!players.add(player)) {
throw new DuplicatePlayerException();
}
}
Set::add
returns true if the set did not already contain the element
3 Comments
String Names = "John";
if (Names.toLowerCase().contains("john")){
System.out.println("yes");
}
You can also use .toLowerCase().contains() to include case sensitive inputs.
List<String> names
which is empty. It should be aclass-level-variable
boolean
for gender is somehow from the last century...names
cannot contain the given name in the method because it will always be empty before yourif
statement that checks if the name is contained. Make it a class attribute...