[英]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.