thomas
thomas

Reputation: 51

Java - How to check if value of an array contains specified value as attribute

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

Upvotes: 1

Views: 1683

Answers (3)

Ruslan
Ruslan

Reputation: 6290

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

Upvotes: 1

Aris Mist
Aris Mist

Reputation: 89

String Names = "John";
    if (Names.toLowerCase().contains("john")){
        System.out.println("yes");
    }

You can also use .toLowerCase().contains() to include case sensitive inputs.

Upvotes: 0

Stultuske
Stultuske

Reputation: 9437

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.

Upvotes: 9

Related Questions