我想讓我的程序比較兩個對象,但我總是收到一條錯誤消息,「找不到符號方法compareTo(Product)」。但是我已經檢查過了,我在Tool類中定義了compareTo方法,如下所示。我一直在收不到符號方法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;
}
}
}
你的產品在哪裏? – Pratik 2015-04-03 04:02:35
您需要檢查compareTo方法this.cost> t.cost – Pratik 2015-04-03 04:03:14