java - 获取用户对 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--;
}
}
解决方案
干得好 。我稍微修改了您的解决方案以使其正常工作!在 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");
}
}
推荐阅读
- codenameone - 用于处理 TextField 和 TextArea 的验证器
- powershell - 使用 CSV 自动删除边界 - Remove-CMBoundary
- android - 如何从我的 Android 应用程序将图像分享到 Snapchat?
- matlab - 将 xlsm 文件读入 MATLAB | 错误文件名必须是字符串
- c++ - 需要帮助解码此 typedef
- java - 这个关键字在运行时和编译时不同
- php - 使用composer在laravel中安装护照时无法分配内存错误
- jenkins - 当没有更改推送到 GitHub 时,阻止 jenkins 管道阶段失败
- python - pandas 按与第一列的绝对相关性对列进行排序
- visual-studio - 当前使用什么可视化工具