Warm tip: This article is reproduced from serverfault.com, please click

Matching Input to ArrayList contents

发布于 2020-11-28 18:24:13

I am trying to loop through an ArrayList contining Football club objects. I am trying to retrieve the name and compare to user input to check if it's a valid team. When checking, it checks first input (team1) and manages to find out if its in the ArrayList or not but for the second one it does not. Even if (team2) exists in the ArrayList as a valid team, it still says it does not exist

 String team1 = userInput.nextLine();

 String team2 = userInput.nextLine();

for(int i =0; i < addStats.size(); i++)
        {
            if(addStats.get(i).getClubName().equals(team1)) {
                for(FootballClub clubs: addStats)
                {
                    if(clubs.getClubName().equals(team2))
                    {
                        break;
                    }
                    else{
                        System.out.println(team2 + " is not a valid team");
                        return;
                    }
                }
                break;
            } else {
                System.out.println(addStats.get(i).getClubName());
                System.out.println(team1 + " is not a valid team");
                return;
            }
        }
Questioner
ASH
Viewed
0
Alex Rudenko 2020-11-29 05:57:21

It seems that the code is failing because it tries to compare the same FootballClub to match both team1 and team2 which cannot be true unless team1 is equal to team2.

If the task is to verify that the list of FootballClub instances contains a club with the given name, a separate simple method should be implemented:

static boolean clubListHasTeam(List<FootballClub> clubs, String team) {
    boolean found = false;

    for (FootballClub club : clubs) {
        if (club.getClubName().equals(team)) {
            found = true;
            break;
        }
    }
    return found;
}

Using Java Stream API helps to make this method more concise:

static boolean clubListHasTeam(List<FootballClub> clubs, String team) {
    return clubs.stream()
                .map(FootballClub::getClubName) // stream of the club names
                .anyMatch(team::equals);  // any club name matched the input name
}

Usage:

String team1 = userInput.nextLine();
String team2 = userInput.nextLine();
boolean valid = true;

if (!clubListHasTeam(addStats, team1)) {
    System.out.println(team1 + " is invalid");
    valid = false;
}
if (!clubListHasTeam(addStats, team2)) {
    System.out.println(team2 + " is invalid");
    valid = false;
}