首页 > 解决方案 > 获取用户对 HashMap 的输入作为键并在 Java 中打印其各自的值

问题描述

我是Java的初学者。我一直在 HashMap 上做这个练习。首先,我需要以 John 1234、Sam 789 的给定格式输入键:值对作为用户输入并创建 HashMap。然后,我需要输入一个名称并检查它是否在创建的 HashMap 中,如果是,则以给定的 John=1234 格式打印其各自的值。但是,无论我输入什么名称,我都会收到其他消息,如以下代码中所述。谁能告诉我我需要如何开发以下代码来获得预期的输出?谢谢你。

    public static void main (String [] arg){ 
    HashMap<String, Integer> phonebook = new HashMap<>();
    Scanner obj = new Scanner(System.in);

    int N = obj.nextInt();
    obj.nextLine();

    while (N > 0) {
        for (int i = 0; i < N; i++) {
            String name = obj.findInLine("\\D+ ");
            int contact = obj.nextInt();
            obj.nextLine();
            phonebook.put(name, contact);
        }   
        String search = obj.nextLine();
            if (phonebook.containsKey(search))
            {
                Integer a = phonebook.get(search);
                System.out.println(search+"="+a);
            }
            else
            {
                System.out.println("Not Found");
            }   
        }
        N--;
    }
}

标签: javahashmap

解决方案


干得好 。我稍微修改了您的解决方案以使其正常工作!在 while 循环中不需要 for 循环。只有while循环很好。

HashMap<String, Integer> phonebook = new HashMap<>();
    Scanner obj = new Scanner(System.in);

    int N = obj.nextInt();
    obj.nextLine();

    while (N-- > 0) {

        String name = obj.findInLine("\\D+");
        name =name.trim();
        int contact = obj.nextInt();
        obj.nextLine();
        phonebook.put(name, contact);
    }
    System.out.println(phonebook);

    // obj.nextLine();

    String search = obj.nextLine();

    if (phonebook.containsKey(search)) {
        Integer a = phonebook.get(search);
        System.out.println(search + "=" + a);
    } else {
        System.out.println("Not Found");
    }
}

在此处输入图像描述


推荐阅读