gpt4 book ai didi

java - 如果字符串与键条目匹配,如何返回键及其值

转载 作者:行者123 更新时间:2023-12-01 19:39:02 25 4
gpt4 key购买 nike

所以我创建了一个类,它创建一个键映射,这些键是菜肴名称的字符串,每个键都有一组字符串值,这些字符串值是菜肴中的成分。我已经设法打印所有键值对,但现在我想要一个将字符串作为参数的方法,然后如果该字符串与键匹配,则打印出键值对,如果不匹配,则显示一条消息说没有找到这样的 key 。

这是我的尝试:

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");
}
}
}

最佳答案

keySet 不带任何参数。该方法返回整个键集,在本例中

[Risotto, Burger, Pizza]

您想要进行查找,即 get 方法。

System.out.println("The ingredients for " + a + " Are: " + recipes.get(a));

关于java - 如果字符串与键条目匹配,如何返回键及其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56036973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com