我刚刚开始学习HashMaps,可以将它们打印出来,但是我在弄清楚如何获取两个值的userInput并将它们存储然后打印出来时遇到了麻烦。
还是我以错误的方式看待这个问题?
System.out.println("Let us know about your pets!");
Map<String, String> pets = new HashMap<>();
String userInput;
String name;
String type;
int numberOfPets = 0;
boolean valid = true;
try (Scanner scnr = new Scanner(System.in)) {
do {
System.out.println("Enter a name: ");
name = userInput.put(scnr.nextLine());
System.out.println("What type of animal is " + (name));
type = userInput.put(scnr.nextLine());
System.out.println("Would you like to enter another? (y/n) ");
numberOfPets++;
} while (scnr.next().equalsIgnoreCase("y"));
}
System.out.println("You entered" + number of pets +"pets.");
for (String key : pets.keySet()) {
System.out.println(key + " is a " + pets.get(key));
}
我希望结果显示为:
输入名称:{用户输入Eustance}
节食是什么类型的动物?
{用户进入巨龙}
您想输入另一只宠物吗?
{是}输入
名称:{用户输入Reepicheep}
Reepicheep是哪种动物:
{用户输入鼠标}
您想输入另一只宠物吗?
{否}
您输入了2只宠物。
输入宠物名称之一(或输入END退出):{用户输入 Reepicheep} Reepicheep是鼠标。
答案 0 :(得分:2)
您需要更改代码以存储名称并在HashMap
中键入内容,如下所示,以便以后可以通过使用pets.get(...)
try (Scanner scnr = new Scanner(System.in)) {
do {
System.out.println("Enter a name: ");
name = scnr.nextLine();
System.out.println("What type of animal is " + (name));
type = scnr.nextLine();
// change made here
pets.put(name, type);
System.out.println("Would you like to enter another? (y/n) ");
numberOfPets++;
// here as well coz scanner was skipping the input
} while (scnr.nextLine().equalsIgnoreCase("y"));
}
答案 1 :(得分:1)
您具有“读取”操作:
pets.get(key)
您只需要一个“写”操作(在您的输入循环中):
pets.put(key, value)
有关完整信息,请查看Map
的JavaDoc,例如:
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
Map
可以完成各种各样的事情!