gpt4 book ai didi

java - 是否可以将字符串与二维数组中的数组名称进行比较?

转载 作者:行者123 更新时间:2023-12-01 08:47:58 25 4
gpt4 key购买 nike

我试图使用用户输入的字符串在二维数组中查找数组。但是,我不断收到“String[][]无法转换为字符串”错误。我可以使用键盘扫描仪和字符串来完成此操作吗?或者是否有更合理的解决方案来解决此问题。

import java.util.Scanner;

public class QandA{

public static void main(String[] args){
String entry;
String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
String[][] Questions = new String[][] { Why };
Scanner k = new Scanner(System.in);
entry = k.next();
for (int i=0 ; i < Questions.length ; i++){
if (entry.equalsIgnoreCase(Questions)){
System.out.println("Test");
break;
}
if (i == Questions.length){
if (!entry.equalsIgnoreCase(Questions)){
System.out.println("Test2");
}
}
}
}
}

编辑:

我已将 2D 数组更改为 HashMap ,但即使在导入 java.util.HashMap 后,仍收到“找不到符号,类 HashMap ”;帮助? [已修复]

import java.util.Scanner;
import java.util.Map;
import java.util.HashMap;
import java.util.*;

public class QandA{

public static void main(String[] args){
String UE;
String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
Map<String, String[]> Questions = new HashMap<>();
Questions.put("Why", Why);
Scanner k = new Scanner(System.in);
UE = k.next();
if(Questions.keySet().stream().filter(UE::equalsIgnoreCase).findFirst().isPresent()) {
System.out.println("Test");
} else {
System.out.println("Test2");
}
}
}

最佳答案

首先,您需要使用Map(而不是String[][])将数组变量的名称映射到其实例:

String[] Why = new String[]{"Because.", "Just Because.", "Why yourself."};
Map<String, String[]> Questions = new HashMap<>();
Questions.put("Why", Why);

接下来,您可以通过多种方式执行Test/Test2检查。这是一种方法:

if(Questions.keySet().stream().filter(entry::equalsIgnoreCase).findAny().isPresent()) {
System.out.println("Test");
} else {
System.out.println("Test2");
}

顺便说一句,您的变量名称非常具有误导性。 “条目”在 map 上下文中具有不同的含义,因为它封装了键+值对。您应该使用有意义的变量名称并遵守有关大小写等的现有 Java 约定。

关于java - 是否可以将字符串与二维数组中的数组名称进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42560732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com