So I need to make a Display method that shows all the DVD objects in an array list by category.
This is exactly what the method should do :
displayDVDsInCategory – this method should have a category as the parameter. It should return an arrayList object with all the DVDs in the specified category. If there is no DVD in the given category, the size of the arrayList will be zero.
Display DVDs By Category - the user should be able to display all DVDs in a particular category. Ask the user to enter a DVD category. If there are no DVDs in the collection matching the requested category, display a message to the user stating that there are no DVDs in the requested category. Otherwise, display a list of DVD titles - one title per line - for the DVDs in the specified category. Display only the titles, and not all of the information.
This is my current method which doesn't work correctly, what am I doing wrong?
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;
}
This is how I call it in my main method class
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));
}
You're returning just a single DVD or null from your function as of now. Assuming your code already compiles fine, this should work fine instead for you -
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;
}
You can pick up keywords from the question which tells you how your method should appear as.
displayDVDsInCategory – this method should have a category as the parameter. It should return an arrayList object with all the DVDs in the specified category. If there is no DVD in the given category, the size of the arrayList will be zero
Since it's telling you to return an ArrayList of DVD object, the return value of your method should be an ArrayList, not a single DVD object:
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
}
You can create a new empty list. While checking through the current list of DVDs, if any of those matches the given category, add them to the new list.
In the end, you return the new list and not a single DVD object. So if none of the DVDs matches, you still return an empty ArrayList.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With