gpt4 book ai didi

java - arraylist:将对象与字符串进行比较

转载 作者:行者123 更新时间:2023-12-01 15:26:28 25 4
gpt4 key购买 nike

大家好,谁能告诉我哪里出了问题?

此类的基本目标是定义一个最喜欢的项目数组列表,在本例中是关于汽车的。汽车对象具有汽车名称和汽车 1-5 的评级。

如何查看字符串是否等于汽车对象评级。我搞乱了将字符串或整数与数组列表中的汽车对象进行比较的部分。我的 equals() 方法有什么问题? contains() 方法可以以同样的方式工作吗?

numberOfItemsOfRating 方法允许用户指定评级,因此该方法返回没有具有评级的汽车。 searchForItems 方法检查指定的字符串描述是否与数组列表中的汽车名称匹配,因此返回数组列表中的汽车。

这里是我的两个带有构造函数和变量的方法的一瞥:

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;
}
}
}
}

最佳答案

您正在根据对象本身进行相等性检查,而您应该根据对象的属性进行相等性检查。在您的特定情况下,您应该查看集合中每个汽车/元素的评级属性。您的代码将如下所示:

final String ratingStr = Integer.toString(rating);

int counter = 0;
for (for final Item car: cars) {
if(ratingStr.equals(car.getRating()) {
++counter;
}

System.out.println("Number of 'cars' with the rating is: " + counter);

两个简短的评论,您应该为您的Item类实现相等方法。但在这种情况下,这并不是问题的真正根源。另外,您在代码中多次提到汽车,但您的 bean 类称为“Item”。您可能想要协调这一点,因为这可能会让阅读您代码的其他人感到困惑。

也不要忘记修复您的 searchForItem 方法,当前您正在测试数组列表与字符串的相等性,这永远不会返回 true。按照与上述相同的方式进行更正,但使用汽车的 description 属性,而不是 rating 属性。

关于java - arraylist:将对象与字符串进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10075442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com