wissam hammoud
wissam hammoud

Reputation: 53

Identify a unique String

I have some strings read in from a file that look like this

"Anderson, T",CWS,SS,...
"Anderson, B",MIA,3B,...
"Galvis, F",CIN,SS,...

I need the user to input a name (such as "Anderson" or "Galvis") and if the name is insufficient to identify a unique player I need to print an error message. So if the user wants to pick "Anderson, T" they would have to specify "Anderson, T").

Currently I have a function that takes in the name ("Anderson, T" or "Anderson, B") and it finds the correct string, the function can be found below

public static boolean findPlayer(String playerName) {
    // Find specified player
    int found = -1;
    for (int j = 0; j < players.size(); j++) {
        if (players.get(j).toString().toLowerCase().contains(playerName.toLowerCase())) {
            found = 0;
            break;
        }
    }
    if (found == 0)
        return true;
    else
        return false;
}

Is there a way for me to modify the code so that it takes in "Anderson" and then print out an error?

Upvotes: 0

Views: 91

Answers (1)

Andreas
Andreas

Reputation: 159086

Since the method is named findPlayer, it should return the found player.

Since you want it to fail if there are multiple player matching the name, you could use an exception to indicate that.

You obviously want to know if no player is found, so you can return null, or change return type to Optional, or throw another exception to indicate that.

Here we'll go with exception for non-unique name, and null for not found:

public static Player findPlayer(String playerName) {
    Pattern nameRegex = Pattern.compile(Pattern.quote(playerName), Pattern.CASE_INSENSITIVE);
    Player foundPlayer = null;
    for (Player player : players) {
        if (nameRegex.matcher(player.toString()).find()) {
            if (foundPlayer != null)
                throw new IllegalArgumentException("Multiple player matches name: " + playerName);
            foundPlayer = player;
        }
    }
    return foundPlayer; // returns null if not found
}

Changed code to use regex for case-insensitive contains logic, so it doesn't create a lot of intermediate lower-case strings during the search.

Upvotes: 1

Related Questions