[英]How can i set the result of a method in a toString
我想在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";
}
順便說一句 -我真的很陌生,完全是個開始。**謝謝。
只需在此處調用您的方法:
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()
方法中使用AGAINST調用方法。 如果只在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()
!
創建屬性finalPrice並將值分配給
this.finalPrice = /*the price*/
並且您的代碼將正常工作
將finalPrice變量存儲為實例變量:
double finalPrice;
public double updatedPrice(double price){
this.price=price;
double ChangePriceRate, ChangePriceAmount;
if(name=="Bamba"){
ChangePriceRate = 0.15;
}else{
ChangePriceRate = 0.05;
}
ChangePriceAmount = price * ChangePriceRate;
if(name=="Bamba"){
finalPrice = price + ChangePriceAmount;
}else{
finalPrice = price - ChangePriceAmount;
}
return finalPrice;
}
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";
}
另一個提示:名稱變量始終以小寫字母開頭,這有助於您區分類名和變量名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.