Java,如何比较字符串和字符串数组

标签 java arrays string equals

我已经在这里搜索了一段时间,但未能找到答案。

我基本上需要使用数组来完成大学的这项作业。然后我应该检查输入(也是一个字符串)是否与存储在字符串数组中的任何内容匹配。

我知道可以使用 .equals() 方法轻松比较字符串。但是,同样的方法不适用于字符串数组。

我为 StackOverflow 创建了以下代码示例,如果您愿意,您可以使用它向我解释。

我做错了什么?

import java.util.Scanner;

class IdiocyCentral {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        /*Prints out the welcome message at the top of the screen*/
        System.out.printf("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
        System.out.printf("%55s", "=================================\n");

        String [] codes = {"G22", "K13", "I30", "S20"};

        System.out.printf("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2], codes[3]);
        System.out.printf("Enter one of the above!\n");

        String usercode = in.nextLine();

        if (codes.equals(usercode)) {
            System.out.printf("What's the matter with you?\n");
        }
        else {
            System.out.printf("Youda man!");
        }

    }
}

如果之前有人问过这个问题而我只是错过了它,我深表歉意,如果它是一个双重问题,我会删除它。

最佳答案

我想您是想检查数组是否包含某个值,是吗?如果是这样,请使用 contains 方法。

if(Arrays.asList(codes).contains(userCode))

关于Java,如何比较字符串和字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8936141/

相关文章:

python - 字符串中特定字母的数量

c - C中字符串的数组和指针表示法之间的区别

java - 在android中读取CSV文件并将其放入Hashmap中

java - 在 JSTL 参数中使用变量

Java gson在序列化时替换成员对象

java - 防止在调整 JButton 的容器大小时调整其大小

Java 文件和 ByteArray 或 InputStream

arrays - 为什么人们不在 for 循环中使用 (int i = length(); i > -1; i--) 而不是创建一个新的长度整数?

arrays - 从数组列表中随机选择 5 个元素,不重复一个元素

python - 日期时间类型错误: not all arguments converted during string formatting