将输入匹配到arraylist内容

ajsxfq5m  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(357)

我正在尝试循环浏览一个包含足球俱乐部对象的数组列表。我试图检索名称并与用户输入进行比较,以检查它是否是有效的团队。在检查时,它检查第一个输入(team1),并设法找出它是否在arraylist中,但对于第二个输入,它不在arraylist中。即使(team2)作为有效的团队存在于arraylist中,它仍然表示它不存在

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

ddarikpa1#

代码似乎失败了,因为它试图比较相同的代码 FootballClub 两者都匹配 team1 以及 team2 除非 team1 等于 team2 .
如果任务是验证 FootballClub 示例中包含具有给定名称的俱乐部,应实现一个单独的简单方法:

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

使用java流api有助于使此方法更加简洁:

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
}

用法:

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

相关问题