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

标签 java arrays if-statement

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

关于java - 如何将用户字符串输入与整个数组中的字符串进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29201636/

相关文章:

java - 弹出菜单显示在屏幕左下方

java - spring security在java区域获取csrf token

javascript - 将二维数组从 PHP 转换为 JS

arrays - 下面的shell脚本中Badly Placed()的错误

c++ - 20 个问题游戏

java - 监控java程序的执行时间分布

java - 类的默认值

PHP:使用给定的字段顺序按比 1 级维度值更深的维度值对多数组进行排序

c++ - 我如何根据宏中的类型做出决定?

jquery - 文本比较 {{if}} JQuery 模板