我的问题是,我在 if 语句中输入 0.2 作为税费和 40.0(长度)* 10.0(宽度)将使价格为 0.3。价格=价格+税应该是0.5,但我一直得到0.4,为什么?完全初学者并感谢任何帮助,我使用 Eclipse IDE。
这是我的司机课程:
package Bag;
public class Driver {
//what is main method for? explain content
//todo auto gen method stub
public static void main(String[] args) {
plasticBag plasticBag = new plasticBag();
plasticBag.setLength(40.0);
plasticBag.setWidth(10.0);
plasticBag.setTax(0.2);
System.out.println(plasticBag.getTax());
System.out.print(plasticBag.getPrice());
}
}
这里是塑料袋类:
package Bag;
public class plasticBag extends Bag {
//instance variable specific to plastic
private double tax;
public void setTax(double tax) {
this.tax = tax;
}
public double getTax() {
return tax;
//why seperate setter and getter?
}
@Override
public double getPrice() {
//what if I don't implement abstract methods?
double area = getLength() * getWidth();
if (area > 250.0) {price = 0.30;}
else {price = 0.20;}
return price + tax;
// why are we getting price 0.4 not 0.5
}
}
这是 bag 抽象类
package Bag;
public abstract class Bag {
private double length;
private double width;
// subclass can access price directly
protected double price;
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
//which is the class level and which is the local?
}
public double getWidth() {
return width;
}
public void setWidth(double with) {
this.width = width;
}
//abstract method
public abstract double getPrice();
}
我尝试检查所有数据类型,它们都是 double 而不是 int,所以这应该不是问题
setWidth()
方法有一个错误。
public void setWidth(double with) {
this.width = width;
}
这会将
width
字段设置为其自身的值(无变化)。
回想一下,类型为 double
的未声明变量将默认为 0
。
所以,在
getPrice()
方法中,计算出的area
不会是预期的400
,而是实际上:40 * 0
。这将进入 else
分支,从而返回 0.4
的最终结果。