[英]Java, how to compare Strings with String Arrays
我一直在这里搜索一段时间,但一直未能找到答案。
我基本上需要使用数组来完成大学的这项任务。 然后我应该检查输入(也是一个String)匹配String数组中存储的内容。
我知道可以通过使用.equals()方法轻松比较Strings。 但是,相同的方法不适用于String数组。
我为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))
现在你似乎在说'这个字符串数组是否等于这个字符串',这当然不会。
也许您应该考虑使用循环遍历您的字符串数组,并检查每个字符串是否与输入的字符串是equals()?
......还是我误解了你的问题?
使用循环迭代codes
数组,询问每个元素是否equals()
到用户usercode
。 如果一个元素相等,则可以停止并处理该情况。 如果所有元素都不等于用户usercode
,那么请执行相应的操作以处理该情况。 在伪代码中:
found = false
foreach element in array:
if element.equals(usercode):
found = true
break
if found:
print "I found it!"
else:
print "I didn't find it"
import java.util.Scanner;
import java.util.*;
public class Main
{
public static void main (String[]args) throws Exception
{
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 ();
for (int i = 0; i < codes.length; i++)
{
if (codes[i].equals (usercode))
{
System.out.printf ("What's the matter with you?\n");
}
else
{
System.out.printf ("Youda man!");
}
}
}
}
如果我正确理解您的问题,您似乎想知道以下内容:
如何检查我的
String
数组是否包含用户usercode
,刚刚输入的String
?
在这里查看类似的问题。 它引用了之前答案中指出的解决方案。 我希望这有帮助。
而不是使用数组,你可以使用ArrayList
直接可以使用contains方法来检查哪些u必须与传递价值ArrayList
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.