1

我收到一个错误,说该.equalsIgnoreCase类型未定义Dog,有没有办法StringArrayList不使用大写的情况下找到一个.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)
4

3 回答 3

4

你不能比较 aDog和 a String,假设Dog有一些String属性,那么你可以这样做:

例子:

if (dogs.get(i).getName().equalsIgnoreCase(toFind)){
       return i;
}
于 2018-04-12T21:20:27.407 回答
0

在 if 循环中的 get(i) 之后添加 .getName()

比如:if (dogs.get(i)..getName().equalsIgnoreCase(toFind))

于 2018-04-12T21:23:42.190 回答
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您只需要根据您的逻辑更改内部代码即可。阅读更多

好的。现在您的代码将是:

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;           
      }
于 2018-04-12T22:33:06.507 回答