gpt4 book ai didi

java - 如何根据条件重写方法

转载 作者:行者123 更新时间:2023-12-02 02:34:56 27 4
gpt4 key购买 nike

在我的预订类(class)中,我有这个方法来计算总金额

public void calcTotal(){
total = amount*priceperbooking;

}

我创建了一个名为 BOOKING_APPLICATION 的子类,我想重写 calcTotal() 方法,如果 amount > 5 那么它必须减去总数的 15%

这是我尝试过的方法,但不起作用:

public void calcTotal(){
if (super.amount>5) {
super.total = super.total-(15/100.0*super.total);
}

}

当我运行它时,它给出的是原始总数,而不是 15%我做错了什么

编辑:这是我的主类的代码

public class Diving_Adventures{
static BOOKING obj1 = new BOOKING();
static BOOKING_APPLICATION obj2 = new BOOKING_APPLICATION();


public static void main(String[] args) {

obj1.setName();
obj1.setNumber();
obj1.setAmount();
obj1.setPriceperbooking();
obj1.calcTotal();
obj2.calcTotal();



JOptionPane.showMessageDialog(null, obj1.toString());
}


}

我假设通过 obj1.calcTotal() 它将计算总数,通过 obj2.calcTotal 它将取出 15%,但它不起作用

这是我的 BOOKING 类的完整代码:

private String name;
private int number;
public int amount;
public double priceperbooking;
public double total;





public String getName() {
return name;
}

public int getNumber() {
return number;
}

public int getAmount() {
return amount;
}

public double getPriceperbooking() {
return priceperbooking;
}

public void setName() {

this.name = JOptionPane.showInputDialog("Enter the name");;
}

public void setNumber() {

this.number = Integer.parseInt(JOptionPane.showInputDialog("Enter the number"));
}

public void setAmount() {

this.amount = Integer.parseInt(JOptionPane.showInputDialog("Enter the amount"));
}

public void setPriceperbooking() {

this.priceperbooking = Double.parseDouble(JOptionPane.showInputDialog("Enter the price per bookin"));;
}


public void calcTotal(){
total = amount*priceperbooking;

}





@Override
public String toString() {
return "Customer name: "+name+"\n"+"number"+ number + "\namount=" + amount +
"\n priceperbooking=" + priceperbooking + "\n total=" + total ;
}

最佳答案

在您的派生类中:

public void calcTotal() {
total = super.calcTotal();
if (amount > 5) {
total = total - (15/100.0 * total);
}
}

如上所述,您没有首先计算总数

关于java - 如何根据条件重写方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46517922/

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