3 回答
TA贡献1852条经验 获得超7个赞
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);
}
}
您需要更改方法以使用实例级别列表:
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);
}
}
所以names每次调用方法时都不会删除的内容。
TA贡献1779条经验 获得超6个赞
您可以考虑Set<Player>代替数组。Set根据定义不能包含重复项。假设Player已实现equals/hashcode您的代码可能如下所示:
Set<Player> players = new HashSet<>();
public void addPlayer(Player player) throws RuntimeException {
if (!players.add(player)) {
throw new DuplicatePlayerException();
}
}
Set::add如果集合尚未包含该元素,则返回 true
TA贡献1848条经验 获得超10个赞
String Names = "John";
if (Names.toLowerCase().contains("john")){
System.out.println("yes");
}
您还可以使用 .toLowerCase().contains() 来包含区分大小写的输入。
添加回答
举报