【问题标题】:How do I compare user string input to the string in an entire array?如何将用户字符串输入与整个数组中的字符串进行比较?
【发布时间】:2015-03-23 00:36:11
【问题描述】:

在我的程序中,我有一个包含团队名称的数组,我想要做的是收集用户输入以检查输入是否与数组中的任何团队名称匹配。如果我加入 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?");
    }
}   

【问题讨论】:

  • 试试看this链接。

标签: java arrays if-statement


【解决方案1】:

使用 java8,这将是一个可能的解决方案:

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

【讨论】:

    【解决方案2】:

    只需将它们放入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?");
    }
    

    【讨论】:

    • 您当然也可以将团队单独放在Set 中,但这会很乏味:)
    • 感谢您的帮助!我还想知道您是否知道一种方法来检查团队名称的输入,而无需将首字母大写即可在“if”中被接受?
    • 最简单的方法是使用例如小写的一切。 Paul's asnwer 的优点是您可以使用equalsIgnoreCase,这对于Set 方法来说(直接)是不可能的。您可以将anyMatch 视为一个循环,但我不认为它在内部使用hashCode
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      相关资源
      最近更新 更多