【问题标题】:LinkedHashMap get(key) return null even when the value is present即使值存在,LinkedHashMap get(key) 也会返回 null
【发布时间】: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


【解决方案1】:

如果我正确理解您的代码,这里的问题是您正尝试使用另一个值 a 检索带有 pair.get(a) 的值(它甚至可能不存在,因为它取决于用户输入!)。

假设你仍然想实现这个功能,你需要有一些类似的东西。

// 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())  + "\".");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    相关资源
    最近更新 更多