繁体   English   中英

如何将用户字符串输入与整个数组中的字符串进行比较?

[英]How do I compare user string input to the string in an entire array?

在我的程序中,我有一个带有团队名称的数组,我想做的是收集用户输入,检查输入是否与数组中的任何团队名称匹配。 如果我提出if语句,我只能一次检查数组中的一个字符串:

if(teamName.equals(teams[0])

但是我想检查数组中的所有字符串,而不是一次检查一个

    Scanner input = new Scanner(System.in);

    String[] teams = new String [20];
    teams[0] = "Arsenal";
    teams[1] = "Aston Villa";
    teams[2] = "Burnley";
    teams[3] = "Chelsea";
    teams[4] = "Crystal Palace";
    teams[5] = "Everton";
    teams[6] = "Hull City";
    teams[7] = "Leicester City";
    teams[8] = "Liverpool";
    teams[9] = "Manchester City";
    teams[10] = "Manchester United";
    teams[11] = "Newcastle United";
    teams[12] = "QPR";
    teams[13] = "Southampton";
    teams[14] = "Sunderland";
    teams[15] = "Spurs";
    teams[16] = "Stoke";
    teams[17] = "Swansea";
    teams[18] = "West Ham";
    teams[19] = "West Brom";

System.out.println("Please enter a team: ");
    String teamName = input.nextLine();

    if(teamName.equals(teams)) {
            System.out.println("You like: " + teamName);
    }
    else {
        System.out.println("Who?");
    }
}   

使用java8,这可能是一种解决方案:

 if(Arrays.stream(teams).anyMatch(t -> t.equals(teamName))) {
     System.out.println("You like: " + teamName);
 } else {
     System.out.println("Who?");
 }

只需将它们放在Set并使用contains方法即可。

因此,请进行以下更改:

Set<String> teamSet = new TreeSet<>();
Collections.addAll(teamSet, teams);

System.out.println("Please enter a team: ");
String teamName = input.nextLine();

if (teamSet.contains(teamName)) {
    System.out.println("You like: " + teamName);
} else {
    System.out.println("Who?");
}

将此方法添加到您的代码中

public boolean arrayContainsTeam(String team)
{
    boolean hasTeam = false;
    for(String aTeam:teams) {
         if(aTeam.equals(team)) {
              return(true);
         }
    }
    return(false);
}

然后更换

if(teamName.equals(teams)) {
        System.out.println("You like: " + teamName);
}
else {
    System.out.println("Who?");
}

if(arrayContainsTeam(teamName)) {
        System.out.println("You like: " + teamName);
}
else {
    System.out.println("Who?");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM