所以我正在做一个项目,其中一个案例要求用户输入一种成分,并打印出所有含有该成分的食谱。
问题是“修改searchByIngredient以返回List变量而不是单个Recipe。List将包含与搜索条件匹配的所有食谱。”
我的问题是我无法打印出所有含有这种成分的食谱。它只打印它找到的第一个。
这是原始代码。它只打印出它找到的包含用户正在搜索的成分的第一个配方。
public Recipe searchByIngredient(String target) {
for (Object ingred : mList) {
Recipe i = (Recipe) ingred;
if (i.hasIngredient(target)) {
return i;
}
}
return null;
}
这是我尝试制作的代码,以便打印出所有含有该成分的食谱。
public List searchByIngredient(String target) {
for (Object ingred : mList) {
Recipe i = (Recipe) ingred;
if (i.hasIngredient(target)) {
return (List) i;
}
}
return null;
}
它会输出:
Please enter an ingredient name:
avocado
Exception in thread "main" java.lang.ClassCastException: Recipe cannot be cast to List
at RecipeBook.searchByIngredient(RecipeBook.java:40)
at RecipeProgram.main(RecipeProgram.java:125)
Java Result: 1
任何帮助将不胜感激!
答案 0 :(得分:2)
发生错误是因为您将配方投射到列表类型。
Recipe i = (Recipe) ingred;
if (i.hasIngredient(target)) {
return (List) i;
实际上,您可以将候选配方添加到列表中,并在完成for循环时将其返回。
像,
public List searchByIngredient(String target) {
List<Recipe> result = new ArrayList<Recipe>();
for (Object ingred : mList) {
Recipe i = (Recipe) ingred;
if (i.hasIngredient(target)) {
// return (List) i;
//Add candidate Recipe into list
result.add(Recipe);
}
}
//return null;
return result;
}