gpt4 book ai didi

java - 我不断收到“无法找到符号方法compareTo”错误

转载 作者:太空宇宙 更新时间:2023-11-04 13:59:46 24 4
gpt4 key购买 nike

我希望我的程序比较两个对象,但我不断收到错误消息“找不到符号方法compareTo(Product)”。但我已经检查过,并且确实在 Tool 类中定义了 CompareTo 方法,如下所示。

public class InventoryDemo
{
public static List<Product> products = new ArrayList<Product>();
public static void main(String [] args)
{

products.add(new Car("Jaguar", 1000000.00));
products.add(new Car("Neon", 17000.00));
products.add(new Tool("JigSaw", 149.18));
products.add(new Car("Jaguar", 110000.00));
products.add(new Car("Neon", 17500.00));
products.add(new Car("Neon", 17875.32));
products.add(new Truck("RAM", 35700.00));
products.add(new Tool("CircularSaw", 200.00));
products.add(new Tool("CircularSaw", 150.00));


InventoryDemo.takeInventory("CircularSaw");
if(products.get(7).compareTo(products.get(8)) == 0)
{
System.out.println("The price of Saw1 and the price of Saw2 are the same.");

}
else if(products.get(7).compareTo(products.get(8)) == 1)
{
System.out.println("Saw1 is more expensive tham Saw2.");
}
else
{
System.out.println("Saw2 is more expensive tham Saw1.");
}


}

public class Tool implements Product, Comparable<Tool>
{

private String name;
private double cost;

public Tool(String name, double cost)
{
this.name = name;
this.cost = cost;
}
public String getName()
{
return name;
}
public double getCost()
{
return cost;
}
public int compareTo(Tool t)
{
if(cost > t.cost)
{
return 1;
}
else if(cost == t.cost)
{
return 0;
}
else
{
return -1;
}
}
}

最佳答案

这可能是因为您将实例保存在接口(interface)支架中,而接口(interface)没有任何有关它的信息。

关于java - 我不断收到“无法找到符号方法compareTo”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29425967/

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