我已经在这里搜索了一段时间,但未能找到答案。
我基本上需要使用数组来完成大学的这项作业。然后我应该检查输入(也是一个字符串)是否与存储在字符串数组中的任何内容匹配。
我知道可以使用 .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/