Java,如何将字符串与字符串数组进行比较
我一直在这里搜索一段时间,但一直未能找到答案。
我基本上需要使用数组来完成大学的这项任务。 然后我应该检查输入(也是一个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"
如果我正确理解您的问题,您似乎想知道以下内容:
如何检查我的
String
数组是否包含用户usercode
,刚刚输入的String
?
在这里查看类似的问题。 它引用了之前答案指出的解决方案。 我希望这有帮助。
您可以直接使用ArrayList
而不是使用数组,并可以使用contains方法检查您使用ArrayList
传递的值。