嗨,大家好,谁能告诉我哪里会出错?arraylist:比较对象与字符串
这个类的基本目的是定义一个喜欢的物品arraylist在这种情况下是关于汽车。汽车物品有汽车名称和汽车1-5的评级。
如何查看字符串是否等于汽车物体等级。 即时通讯组件将你比较一个字符串或整数的数组列表中的汽车对象。我的equals()方法有什么问题?可以包含()方法的工作方式相同吗?
numberOfItemsOfRating方法允许用户指定评级,因此该方法返回评级为no的汽车。 searchForItems方法检查指定的字符串描述是否与数组列表中的汽车名称相匹配,并因此以arraylist方式返回汽车。
这里是我的两个方法与构造函数和变量一瞥:
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;
}
}
}
}
实现等于()方法为汽车 – mishadoff 2012-04-09 15:23:32
这就是我所做的,但它似乎并没有工作 – Danial 2012-04-09 15:25:06
您正在比较一个项目对象与整数 - 这是你的意图? – tdrury 2012-04-09 15:25:12