Calling a method in java and returning beer cost

后端 未结 3 1674
轻奢々
轻奢々 2021-01-29 13:02

What I am supposed to do:

Add some necessary statements to the printOrderCost() method in the main class so that this method computes and p

相关标签:
3条回答
  • 2021-01-29 13:13

    Your code looks fine to me. To call getCost() in toString() method, simply just call it with getCost().

    So your toString() method should be something like this:

    public toString(){
        String s;
        s = brand + " ";
        s += quantity + " " ;
        s += itemCost + " ";
        s += getCost();
    
        return s;
    }
    

    Hope this is what you're looking for :)

    0 讨论(0)
  • 2021-01-29 13:29

    From the code you have supplied, the getCost method "looks" fine

    Your toString method should simply need to be appended to your return String s

    public String toString()  // not necessary to format the output
    {
        String s;
        s = brand + " ";
        s += quantity + " " ;
        s += itemCost + " ";
        s += getCost();
        return s;
    }
    

    You might also like to take a look at NumberFormat, which will allow you to control the output format, just in case you get a funny looking value ;)

    0 讨论(0)
  • 2021-01-29 13:32

    It is generally a bad idea to add strings up like you did, as Java will create a unique String for each addition, which causes some unnecessary overhead. You can either use a StringBuilder as a general-purpose tool, or, if you know the exact format of how the String should look like, you can use String.format(...).

    Example:

    public toString() {
      return String.format("%-10s %2d %6.2f %6.2f", brand, quantity, itemCost, getCost());
    }
    
    0 讨论(0)
提交回复
热议问题