Hi guys could anyone tell me where im going wrong?
The basic aim of this class is to define a favourite items arraylist which in this case is about cars. The cars objects have a car name and a rating for car 1-5.
how do you see if a string is equal to the car objects rating. im messing up the part where you compare a string or int to an car object in array list. what is wrong with my equals() method? can contains() method work the same way?
The numberOfItemsOfRating method allows user to specify rating and hence the method returns the no cars with the rating. the searchForItems method checks if String description specified matches the cars name in array list, and hence returns the car in arraylist.
here is a glimpse of my two methods with constructors and variables:
public class FavouriteItems
{
private ArrayList<Item> cars;
/**
* Constructor for objects of class FavouriteItems
*/
public FavouriteItems()
{
cars= new ArrayList<Item>();
}
/**
* Add a new Item to your collection
* @param newItem The Item object to be added to the collection.
*/
public void addToFavourites(Item newItem)
{
cars.add(newItem);
}
/**
* Count the number of Items with a given rating
* @return The number of Items (Item objects)
* whose rating is rating (could be 0).
* If the rating parameter is outside the valid
* range 1..5 then print an error message and return 0.
*/
public int numberOfItemsOfRating(int rating)
{
int counter = 0;
if(rating >= 1 && rating <=5)
{
for ( int i =0; i < cars.size(); i++)
{
int num = rating;
String al = Integer.toString(rating);
if(cars.get(i).equals(al))
{
counter++;
}
}
}
else
{
System.out.println("No cars match your ratings");
counter = 0;
}
return counter;
}
/**
* Find the details of a Item given its description
* @return Item object if its description is in the collection
* or null if there is no item with that description
*/
public Item searchForItem(String description)
{
for(int i=0; i<cars.size(); i++)
{
if(cars.equals(description))
{
return cars.get(i);
}
else
{
return null;
}
}
}
}
Item-class?