【问题标题】:java-Modify a search method to return a list of recipes that contain an ingredientjava-修改搜索方法以返回包含某成分的食谱列表
【发布时间】:2013-11-17 03:25:45
【问题描述】:

所以我正在做一个项目,其中一个案例要求用户输入一种成分,它会打印出所有包含该成分的食谱。

问题是“修改 searchByIngredient 以返回列表变量而不是单个食谱。列表将包含与搜索条件匹配的所有食谱。”

我的问题是我无法让它打印所有包含该成分的食谱。它只打印找到的第一个。

这是原始代码。它只打印出它找到的第一个包含用户正在搜索的成分的食谱。

  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

任何帮助将不胜感激!

【问题讨论】:

    标签: java search


    【解决方案1】:

    发生错误是因为您将 Recipe 转换为 List 类型。

     Recipe i = (Recipe) ingred;
     if (i.hasIngredient(target)) {
        return (List) i;
    

    其实,你可以将候选Recipe添加到一个List中,并在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;
         }
    

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多