Java,如何比较字符串和字符串数组 [英] Java, how to compare Strings with String Arrays
问题描述
我在这里搜索了一段时间,但一直没有找到答案.
I have been searching here for some time but haven't been able to find the answer to it.
我基本上被要求使用一个数组来完成大学的这项作业.然后我应该检查输入(它也是一个字符串)是否与字符串数组中存储的任何内容相匹配.
I am basically required to use an array for this assignment from college. And then I am supposed to check that the input (which is also a String) matches whatever's stored within the String array.
我知道可以使用 .equals() 方法轻松比较字符串.但是,同样的方法不适用于 String 数组.
I know one can easily compare Strings by using the .equals() method. However, the same method is not working with the String array.
我为 StackOverflow 创建了以下代码示例,以便您可以使用它向我解释(如果您愿意).
I created the following example of code for the purpose of StackOverflow so you can use it to explain it to me, if you'd like.
我做错了什么?
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!");
}
}
}
如果之前有人问过这个问题,我很抱歉,我只是错过了,如果是双重问题,我会删除它.
I apologize if this has been asked before and I just missed it, if its a double question, I will remove it.
推荐答案
我想您想检查数组是否包含某个值,是吗?如果是这样,请使用 contains
方法.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains
method.
if(Arrays.asList(codes).contains(userCode))
这篇关于Java,如何比较字符串和字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!