英文:
LinkedHashMap get(key) return null even when the value is present
问题
任务是询问一些随机卡片的定义。在我介绍了这些卡片并且访问了这个方法后,与键对应的值存在,但仍然返回 null。
pair.get(a) 总是打印 null
public static void ask() {
System.out.println("要询问多少次?");
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("打印 \"" + values[retur] + "\" 的定义:");
String a = scan.nextLine();
System.out.println(a.equals(pair.get(values[retur])) ? "回答正确。" :
"回答错误。正确答案是 \"" + pair.get(values[retur]) +
"\", 你刚刚写下的是 \"" + pair.get(a) + "\" 的定义。");
}else
break;
}
英文:
The task is to ask for a definitions of some random cards. After I introduce the cards and I access this method, the value corresponding to the key is present and it still returns null.
pair.get(a) always printing 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;
}
答案1
得分: 0
如果我正确理解你的代码,问题在于你正在尝试使用pair.get(a)
来检索一个值,而使用了另一个值a
(这个值甚至可能不存在,因为它取决于用户输入!)。
假设你仍然想要实现这个功能,你需要有类似以下的代码。
// 获取由a引用的键(如果存在)
var aKey = pair.entrySet()
.stream()
.filter(entry -> a.equals(entry.getValue()))
.map(Map.Entry::getKey)
.findFirst();
// 如果值a对应的键不存在,则打印"错误的输入"(你可以根据需要进行处理),否则打印原始语句
if (aKey.isEmpty()) {
System.out.println("错误的输入!");
} else {
System.out.println(a.equals(pair.get(values[retur])) ? "正确的答案。" :
"错误的答案。正确的答案是 \"" + pair.get(values[retur]) +
"\", 你刚刚写了 \"" + pair.get(aKey.get()) + "\" 的定义。");
}
英文:
If I understand your code correctly the problem here is that you are trying to retrieve a value with pair.get(a)
using another value a
(which may not even exist since it depends on user input!).
Assuming you still want to achieve this functionality, you need to have something along these lines.
// Get the key referenced by a (if exists)
var aKey = pair.entrySet()
.stream()
.filter(entry -> a.equals(entry.getValue()))
.map(Map.Entry::getKey)
.findFirst();
// If the key for value a does not exist, print incorrect input (you can handle this however you like), otherwise print original statement
if (aKey.isEmpty()) {
System.out.println("Incorrect input!");
} else {
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(aKey.get()) + "\".");
}
专注分享java语言的经验与见解,让所有开发者获益!
评论