Java - 如何检查数组的值是否包含指定的值作为属性

我有一组 Player 对象。球员有名字,当我添加球员时,我想检查球员名字是否已经存在。以下代码永远不会引发异常,它只会添加重复的玩家。


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);

    }

}


芜湖不芜
浏览 148回答 3
3回答

慕姐4208626

public void addPlayer(String name, boolean gender, int index)&nbsp; throws RuntimeException {&nbsp; &nbsp; List<String> names = new ArrayList<>(); // you create a new instance of the list each time you call it, so it'll always be empty&nbsp; &nbsp; if (names.contains(name)) // your empty list does not contain anything&nbsp; &nbsp; &nbsp; &nbsp; throw new DuplicatePlayerException();&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; players[index] = new Player(name, gender);&nbsp; &nbsp; &nbsp; &nbsp; names.add(name);&nbsp; &nbsp; }}您需要更改方法以使用实例级别列表:private List<String> names = new ArrayList<>();public void addPlayer(String name, boolean gender, int index)&nbsp; throws RuntimeException {&nbsp; &nbsp; if (names.contains(name))&nbsp; &nbsp; &nbsp; &nbsp; throw new DuplicatePlayerException();&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; players[index] = new Player(name, gender);&nbsp; &nbsp; &nbsp; &nbsp; names.add(name);&nbsp; &nbsp; }}所以names每次调用方法时都不会删除的内容。

哆啦的时光机

您可以考虑Set<Player>代替数组。Set根据定义不能包含重复项。假设Player已实现equals/hashcode您的代码可能如下所示:Set<Player> players = new HashSet<>();public void addPlayer(Player player)&nbsp; throws RuntimeException {&nbsp; &nbsp; if (!players.add(player)) {&nbsp; &nbsp; &nbsp; &nbsp; throw new DuplicatePlayerException();&nbsp; &nbsp; }}Set::add如果集合尚未包含该元素,则返回 true

慕桂英546537

String Names = "John";&nbsp; &nbsp; if (Names.toLowerCase().contains("john")){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("yes");&nbsp; &nbsp; }您还可以使用 .toLowerCase().contains() 来包含区分大小写的输入。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java