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.
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
-
even though this is indeed a good remark, if he had used a Set instead of a List, he still would have had the same problemStultuske– Stultuske03/05/2019 09:53:13Commented Mar 5, 2019 at 9:53
-
@Stultuske I suggest to use Set instead of array. There is no List in my answerRuslan– Ruslan03/05/2019 10:43:23Commented Mar 5, 2019 at 10:43
-
I was referring to the code of the OP, where he used a list. In your answer, you fixed his error, yet you don't speak of that, you only explain the benefit of using a Set (after fixing his error)Stultuske– Stultuske03/05/2019 10:47:38Commented Mar 5, 2019 at 10:47
String Names = "John";
if (Names.toLowerCase().contains("john")){
System.out.println("yes");
}
You can also use .toLowerCase().contains() to include case sensitive inputs.
-
This would make a good comment, but it is not related to the actual problem the OP encountered.Stultuske– Stultuske03/05/2019 09:58:42Commented Mar 5, 2019 at 9:58
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...