程序保存'null'或未在HashMap中保存信息

问题描述 投票:-3回答:2

我需要使用HashMap制作某种电话簿。

如果输入数字,程序必须要求输入名称并保存键和值。如果我输入姓名,那么我必须输入数字。

数字是键,名称是值。

else if (isPhone(input)){
     if (phoneBook.containsKey(input)){
        System.out.println("This number reserve by => " + phoneBook.get(input));
        } else {
               System.out.println("Enter number's owner: " + input);
               String name = scanner.nextLine();
               if (isName(name)){
                  System.out.println("Accept!");
                  phoneBook.put(input, name);

嗯,它保存了密钥,但没有保存值。Happens this

Link to full code at GitHub

java
2个回答
1
投票

就像您自己说的一样:数字是关键,名称是价值。但是您尝试在此处为get方法指定一个名称作为参数:

if (phoneBook.containsValue(input)){
    System.out.println("This person own number => " + phoneBook.get(input));
}

一种存储和检索数字和名称的有效方法是拥有两个HashMap。一个以电话号码为键,另一个以名称为键。


0
投票

您的代码中的第44行 System.out.println("This person own number => " + phoneBook.get(input)); 是错误的。

这将尝试通过该值获取地图条目,并且为null。

对于Java 8使用 Set set = phoneBook.entrySet().stream().filter(entry -> Objects.equals(entry.getValue(), input)).map(Map.Entry::getKey).collect(Collectors.toSet()); System.out.println("This person own number => " + set.toArray()[0]); 例如。

可以找到其他选项here

© www.soinside.com 2019 - 2024. All rights reserved.