java - 如何在 toString 中设置方法的结果

标签 java oop methods 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";
    }

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/

相关文章:

java - HTML 标签被从字符串中剥离

java - 如何在没有硬编码路径的情况下从 64 位 java 进程启动 32 位 java 进程

javascript - CoffeeScript 循环方法

methods - Kotlin 方法引用代替 lambda

java - 如何在 ResourceChangeListener(eclipse 插件)中添加标记?

java - Spring:如何使用 CrudRepository 默认返回具有实体连接引用的所有对象

c - 卢阿 :new from C API

C#:可选方法

c++ - 在 C++ 中继承 C 结构并将其传递回 C 库是否安全?

c# - 当只调用一次时,创建辅助方法是否仍然有意义?