【发布时间】:2020-04-08 15:40:00
【问题描述】:
任务是询问一些随机卡片的定义。在我引入卡片并访问此方法后,与键对应的值存在,它仍然返回 null。
pair.get(a) 总是打印 null
public static void ask() {
System.out.println("How many times to ask?");
int ask = scan.nextInt();
scan.nextLine();
Random random = new Random();
Object[] values = pair.keySet().toArray();
int retur = random.nextInt(values.length);
int i = 0;
for (String iterator : pair.keySet()) {
if (i <= ask) {
System.out.println("Print the definition of \"" + values[retur] + "\":");
String a = scan.nextLine();
System.out.println(a.equals(pair.get(values[retur])) ? "Correct answer." :
"Wrong answer. The correct one is \"" + pair.get(values[retur]) +
"\", you've just written the definition of \"" + pair.get(a) + "\".");
}else
break;
}
【问题讨论】:
-
我猜错误来自
pair.get(a)?键a不能保证在您的字典中,正如我所知的焦油。它不是来自values数组。a是在控制台上输入的。这可以是任何东西。此外,如果您在字典中的键不是字符串,那么pair.get(a)将始终返回null。 -
欢迎来到 Stack Overflow。请通过tour 了解 Stack Overflow 的工作原理,并阅读How to Ask 以了解如何提高问题的质量。然后edit你的问题包含你的源代码作为minimal reproducible example,它可以被其他人编译和测试。
标签: java linkedhashmap