在java中调用方法并返回啤酒成本

我该怎么做:

向主类中的printOrderCost()方法添加一些必要的语句,以便此方法计算并打印订单中所有啤酒项目的总成本。 (此方法为每个啤酒项调用getCost()方法,累计所有getCost()值的总和,然后打印总和 – 所有啤酒对象的总成本。)

码:

 public static void printOrderCost(Beer[] order) { double totalCost; int count; } } public double getCost() { double cost; cost = quantity * itemCost; return (cost); } public String toString() // not necessary to format the output { String s; s = brand + " "; s += quantity + " " ; s += itemCost + " "; s += getCost(); return s; } 

输出:

 Bud 5 3.0 15.0 Canadian 5 1.0 5.0 Blue 3 2.0 6.0 White Seal 4 1.0 4.0 Bud Light 1 2.0 2.0 

你的代码对我来说很好。 要在toString()方法中调用getCost(),只需使用getCost()调用它即可。

所以你的toString()方法应该是这样的:

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

希望这是你要找的:)

从你提供的代码中, getCost方法“看起来很好”

您的toString方法应该只需要附加到return String

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

您可能还想看看NumberFormat ,它将允许您控制输出格式,以防您获得有趣的外观值;)

像往常一样添加字符串通常是一个坏主意,因为Java会为每次添加创建一个唯一的字符串,这会导致一些不必要的开销。 您可以使用StringBuilder作为通用工具,或者,如果您知道String的外观的确切格式,则可以使用String.format(…)。

例:

 public toString() { return String.format("%-10s %2d %6.2f %6.2f", brand, quantity, itemCost, getCost()); }