【发布时间】:2014-12-17 16:33:47
【问题描述】:
今天我正在开发一个新程序,以在充满数据的文件中找到最便宜的披萨。我完全被困在一个问题上,它使用的是 compareTo 方法。我在我的资源类中创建了它,但我没有收到错误说不能取消引用双精度,我查看了这个问题,但仍然没有任何帮助。我不是最高级的程序员,也不了解其他资源上的许多复杂答案。我的程序规格如下:
B.廉价披萨.java 一种。 Objective – 在 Pizza.java 中实现 Comparable 接口。 湾。作业——使用你复制到第 10 章的 Pizza.java 文件。实现 Comparable 接口并添加 compareTo() 方法。应该使用这个 compareTo() 帮助您在 Pizza.txt 中找到最便宜的披萨。 编写CheapPizza.java 客户端类来测试新版本的Pizza.java。便宜的披萨会 从文件中读取比萨饼,并使用 compareTo() 方法。创建一个 Pizza 对象来保存最便宜的 Pizza 和一个 Pizza 对象 从文件中读取比萨饼。使用 compareTo() 比较最便宜的披萨和 比萨从文件中读取。如果从文件中读取的比萨更便宜,则更改最便宜的 比萨。 一种。输入 – Blackboard 上的 Pizzas.txt 文件。 湾。输出 - 应完全以如下所示的格式出现: 最便宜的披萨:9英寸橄榄披萨售价7.99美元
compareTo 方法的代码在我的代码底部,有人可以向我解释一下我做错了什么吗?感谢您的宝贵时间,祝您有美好的一天! ~
public class Pizza {
private int size;
private double cost;
private String topping;
public Pizza(int s, double c, String t)
{
size = s;
cost = c;
topping = t;
}
public Pizza(String t, int s, double c) //.equals Method For Comparing Pizza for ''PizzaMatch''
{
topping = t;
size = s;
cost = c;
}
public Pizza()
{
size = 10;
cost = 9.00;
topping = "Cheese";
}
public String toString()
{
return String.format("%d inch %s pizza will cost $%.2f", size, topping, cost);
}
public int getSize()
{
return size;
}
public void setSize(int s)
{
size = s;
}
public double getCost()
{
return cost;
}
public void setCost(Double c)
{
cost = c;
}
public String getTopping()
{
return topping;
}
public void setTopping(String t)
{
topping = t;
}
public boolean equals(Object obj) //.equals Method For Comparing Pizza in "PizzaMatch"
{
if(!(obj instanceof Pizza))
throw new IllegalArgumentException("Parameter must be of Pizza!");
Pizza temp = (Pizza) obj;
if (this.topping.equals(temp.topping) && this.size == temp.size && this.cost == temp.cost)
return true;
else
return false;
}
//============================================================================================
public int compareTo(Object obj){
if(!(obj instanceof Pizza))
throw new IllegalArgumentException
("Parameter must be a Pizza");
Pizza temp = (Pizza) obj;
if (this.cost.compareTo(temp.cost) < 0) //this comes 1st
return -1;
else if(this.cost.compareTo(temp.cost) > 0) //temp comes 1st
return 1;
else //this and temp are equal
return 0;
}
}
【问题讨论】:
-
您不能将
compareTo与原语一起使用,doubles 是。只需直接比较它们,例如this.cost < temp.cost. -
非常感谢您提供的信息!
标签: java computer-science compareto