我收到错误消息称.equalsIgnoreCase
未定义类型Dog
,是否有任何方法可以在String
中找到ArrayList
而忽略大写而不使用.equalsIgnoreCase
?
public static int findDog(String toFind, ArrayList<Dog> dogs)
{
for (int i = 0 ; i < dogs.size() ; i++)
{
if (dogs.get(i).equalsIgnoreCase(toFind))
{
return i;
}
}
return -1;
}
Dog
有一个像这样的公共构造函数:
public Dog(String name, double age, double weight)
答案 0 :(得分:4)
您无法将java.lang.String
与Dog
进行比较,假设String
具有某些Dog
属性,那么您可以执行以下操作:
示例:强>
String
答案 1 :(得分:0)
在if循环
中的get(i)之后添加.getName()喜欢:if(dogs.get(i).. getName()。equalsIgnoreCase(toFind))
答案 2 :(得分:0)
请注意,.equalsIgnoreCase logic
将与Dog一起使用,但不像你做的那样。这就是你需要做的事情。
我们想说2 dogs are same if they have same Name
。
然后修改您的Dog类,如下所示:
public class Dog implements Comparable<Dog> {
private String name;
private double age;
private double weight;
public Dog(String name, double age, double weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getAge() {
return age;
}
public void setAge(double age) {
this.age = age;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public int compareTo(Dog anotherDogToCompare) {
return this.getName().toLowerCase().compareTo(anotherDogToCompare.getName().toLowerCase());
}
}
现在,无论何时,你想比较2只狗,如果它给出compareTo
上面的0
,那么2只狗是相同的,否则不一样。请注意,如果他们有相同的名字,我假设2只狗是相同的。
如果这不是平等标准,则无需担心。根据您的逻辑,您需要更改的是compareTo
内的代码。 Read More
好。现在您的代码将是:
public static int findDog(String toFind, ArrayList<Dog> dogs)
{
for (int i = 0 ; i < dogs.size() ; i++)
{
if (dogs.get(i).compareTo(toFind) == 0) // Only this changes
{
return i;
}
}
return -1;
}