我想在 ToString 中显示方法的结果,我该怎么做? 到目前为止,这是我的代码: 你可以在底线看到我不知道要写什么来获取“updatedPrice”的结果,你能帮忙吗?
public double updatedPrice(double price){
this.price=price;
double ChangePriceRate, ChangePriceAmount, finalPrice;
if(name=="Bamba"){
ChangePriceRate = 0.15;
}else{
ChangePriceRate = 0.05;
}
ChangePriceAmount = price * ChangePriceRate;
if(name=="Bamba"){
finalPrice = price + ChangePriceAmount;
}else{
finalPrice = price - ChangePriceAmount;
}
}
public String toString (){
return "Name of the Snack: "+name+ "\n"+
"Name of the Company: "+comp+ "\n"+
"Price before discount: "+this.price+ "\n"+
"Price after discount: "+ **finalPrice?** + "\n";
}
b.t.w - 我对此真的很陌生,完全是初学者。** 谢谢。
最佳答案
只需在那里调用您的方法即可:
public String toString (){
return "Name of the Snack: " + name + "\n" +
"Name of the Company: " + comp + "\n" +
"Price before discount: " + this.price+ "\n" +
"Price after discount: " + updatedPrice(this.price) + "\n";
}
<小时/>
注意:
一般来说,我建议不要在 toString() 方法中调用方法。
如果您只显示 toString()
中类的状态,从而只显示现有字段的值,那就更好了。
这意味着您应该引入一个名为 finalPrice
的字段并在其中存储您的值。
之后,您可以使用 toString()
方法显示该值:
public static class MyClass {
private String name;
private String comp;
private double price;
private double finalPrice; // <-- Field for final price
[...]
public void updatePrice(double price) {
this.price = price;
double changePriceRate;
double changePriceAmount;
if ("Bamba".equals(this.name)) { // <-- Use equals()!
changePriceRate = 0.15;
} else {
changePriceRate = 0.05;
}
changePriceAmount = price * changePriceRate;
if ("Bamba".equals(this.name)) { // <-- Use equals()!
finalPrice = price + changePriceAmount;
} else {
finalPrice = price - changePriceAmount;
}
}
public String toString() {
return "Name of the Snack: " + name + "\n" +
"Name of the Company: " + comp + "\n" +
"Price before discount: " + price + "\n" +
"Price after discount: " + finalPrice + "\n";
}
}
<小时/>
奖励积分:
不要使用 ==
来比较字符串,如果要比较字符串的内容,请使用 equals()
!
关于java - 如何在 toString 中设置方法的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41263444/