程序在HashMap中保存“空”或未保存信息

我需要使用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);

好吧,它保存了密钥,但没有保存值。

程序在HashMap中保存“空”或未保存信息

Link to full code at GitHub

xjdyjk2007 回答:程序在HashMap中保存“空”或未保存信息

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

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

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

,

代码中的第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

本文链接:https://www.f2er.com/3151398.html

大家都在问