gpt4 book ai didi

java - 我将如何使用 if 语句来更改属性的值?

转载 作者:行者123 更新时间:2023-11-30 06:32:35 24 4
gpt4 key购买 nike

我希望能够根据某些要求给出特定的折扣值,例如以下年龄:> 25 岁和专业 = 教师/教授获得 10% 的折扣,年龄 < 25 和 gradepoint > 7 获得 25% 的折扣

到目前为止,这是我使用双 OO 范式的代码:

public class customer {

//attribute definitions
private String name;
private String address;
private String profession;
private Integer age;
private Integer gradepoint;
private double discount;

//constructor
public customer(String newName, String newAddress, String newProfession, Integer newAge, Integer newGradepoint, double newDiscount)
{
setName(newName);
setAddress(newAddress);
setProfession(newProfession);
setAge(newAge);
setGradepoint(newGradepoint);
setDiscount (newDiscount);
}

//getters
public String getName()
{ return name;}
public String getAddress()
{ return address;}
public String getProfession()
{ return profession;}
public Integer getAge()
{ return age;}
public Integer getGradepoint()
{ return gradepoint;}
public double getDiscount()
{ return discount;}

//setters
public void setName (String newName)
{ name = newName;}
public void setAddress (String newAddress)
{ address = newAddress;}
public void setProfession (String newProfession)
{ profession = newProfession;}
public void setAge (Integer newAge)
{ age = newAge;}
public void setGradepoint (Integer newGradepoint)
{ gradepoint = newGradepoint;}
public void setDiscount (double newDiscount)
{ discount = newDiscount;}

//methods


}

我是否需要创建一个名为折扣或每种类型的折扣的子类?或者我可以直接在这个客户类中写一个方法来控制折扣?

最佳答案

write a method directly into this customer class to control the discount?

这个。使其成为计算字段。杀死 setDiscount 函数,杀死 discount 变量,并将 getDiscount 函数变成类似这样的东西:

public double getDiscount() {
if (...) return ...;
if (....) return ...;
...
}

...除非你想把它作为默认折扣,并且仍然允许修改,在这种情况下,将 discount 保留为一个属性,并将整个逻辑移动到构造函数中,有条件 setDiscount() 调用。

关于java - 我将如何使用 if 语句来更改属性的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8718812/

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