【问题标题】:Having trouble displaying all DVD objects by title in Array List在数组列表中按标题显示所有 DVD 对象时遇到问题
【发布时间】:2018-04-14 12:39:10
【问题描述】:

所以我需要创建一个 Display 方法,按类别显示数组列表中的所有 DVD 对象。

这正是该方法应该做的:

displayDVDsInCategory – 这个方法应该有一个类别作为参数。它 应该返回一个 arrayList 对象,其中包含指定类别中的所有 DVD。如果给定类别中没有 DVD,则 arrayList 的大小将为零。

按类别显示 DVD - 用户应该能够显示特定类别中的所有 DVD 类别。要求用户输入 DVD 类别。如果收藏中没有 DVD 匹配请求的类别,向用户显示一条消息,说明没有 请求类别中的 DVD。否则,显示 DVD 标题列表 - 每个标题一个 行 - 用于指定类别中的 DVD。只显示标题,而不是全部 信息。

这是我当前的方法无法正常工作,我做错了什么?

public DVD displayDVDsInCategory(String category) 
{
    for (int i=0;i<arraylist.size();i++)
    {
        if(category.equalsIgnoreCase(arraylist.get(i).getCategory())){
            return arraylist.get(i);
        }
    }
    return null;
}

这就是我在主方法类中的调用方式

else if(selection==4){
   String ser;
   System.out.println("Please enter a DVD category to search for:");
   kbd.nextLine();
   ser=kbd.nextLine();
   System.out.println(x.displayDVDsInCategory(ser));
}

【问题讨论】:

    标签: java arraylist methods


    【解决方案1】:

    到目前为止,您的函数只返回了一个 DVDnull。假设您的代码已经可以正常编译,那么这对您来说应该可以正常工作 -

    public List<DVD> displayDVDsInCategory(String category) {
        List<DVD> result = new ArrayList<>();
        for (int i = 0; i < arraylist.size(); i++) {
            if(category.equalsIgnoreCase(arraylist.get(i).getCategory())) {
               result.add(arraylist.get(i));
            }
        }
        return result;
    }
    

    【讨论】:

      【解决方案2】:

      您可以从问题中选择关键字,该关键字告诉您您的方法应该如何显示。

      displayDVDsInCategory – 这个方法应该有一个类别作为参数。它应该返回一个 arrayList 对象,其中包含指定类别中的所有 DVD。如果给定类别中没有 DVD,则 arrayList 的大小将为零

      由于它告诉您返回 DVD 对象的 ArrayList,因此您的方法的返回值应该是 ArrayList,而不是单个 DVD 对象:

      public ArrayList<DVD> displayDVDsInCategory(String category)   //return DVD list
      {
          ArrayList<DVD> newList = new ArrayList<DVD>();
          for (DVD dvd : arraylist)    //for each dvd in your current list
              if(category.equalsIgnoreCase(dvd.getCategory())){     //if category matches
                  newList.add(dvd);                                 //add to new list
          return newList;                                           //return DVD list
      }
      

      您可以创建一个新的空列表。在检查当前 DVD 列表时,如果其中任何一个与给定类别匹配,则将它们添加到新列表中。

      最后,您返回的是新列表,而不是单个 DVD 对象。因此,如果没有任何 DVD 匹配,您仍然会返回一个空的 ArrayList。

      【讨论】:

        【解决方案3】:

        我不确定出了什么问题,但您的描述与您的代码不符。如果您想返回 DVD 列表,您的代码是错误的,它只返回类别与作为参数传递的类别匹配的第一张 DVD。

        顺便说一句,如果您使用的是 Java 8,您可以对您的代码进行一些改进。请参阅下面的 sn-p。

        public static List<String> displayDVDsInCategory(final String category) {
            return arraylist.stream()
                 .filter(obj -> obj.equalsIgnoreCase(category))
                 .collect(Collectors.toList());
        }
        

        【讨论】:

          猜你喜欢
          • 2020-01-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-26
          • 1970-01-01
          • 2023-03-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多