【发布时间】:2019-05-08 17:57:06
【问题描述】:
所以我创建了一个类,它创建一个键映射,这些键是菜肴名称的字符串,每个键都有一组字符串值,它们是菜肴中的成分。我已经设法打印出所有的键值对,但现在我想要一个将字符串作为参数的方法,然后如果该字符串与键匹配,则打印出键值对,如果不匹配,则显示一条消息说没有找到这样的密钥。
这是我的尝试:
public void printMapValue(String a) {
if (recipes.containsKey(a)) {
System.out.println("The ingredients for " + a + " Are: " + ingredients);
} else {
System.out.println("That string does not match a record");
}
}
到目前为止,这也是我的完整类代码,在 printMapVale() 方法之前,所有代码都按预期工作
public class Recipe {
Map<String, Set<String>> recipes;
public Recipe() {
this.recipes = new HashMap<>();
}
public void addData() {
Set<String> ingredients = new HashSet<>();
ingredients.add("Rice");
ingredients.add("Stock");
recipes.put("Risotto", ingredients);
ingredients = new HashSet<>();
ingredients.add("Bun");
ingredients.add("Patty");
ingredients.add("Cheese");
ingredients.add("Lettuce");
recipes.put("Burger", ingredients);
ingredients = new HashSet<>();
ingredients.add("Base");
ingredients.add("Sauce");
ingredients.add("Cheese");
ingredients.add("Pepperoni");
recipes.put("Pizza", ingredients);
}
public void printMap() {
for (String recipeKey : recipes.keySet()) {
System.out.print("Dish : " + String.valueOf(recipeKey) + " Ingredients:");
for (String dish : recipes.get(recipeKey)) {
System.out.print(" " + dish + " ");
}
System.out.println();
}
}
public void printMapValue(String a) {
if (recipes.containsKey(a)) {
System.out.println("The ingredients for " + a + " Are: " + recipes.keySet(a));
} else {
System.out.println("That string does not match a record");
}
}
}
【问题讨论】:
-
不确定我是否理解了这个问题,是
if块内的Set<String> ingredients = recipes.get(a);吗?