-2

我应该做什么:

在主类的方法中添加一些必要的语句,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
4

3 回答 3

0

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

例子:

public toString() {
  return String.format("%-10s %2d %6.2f %6.2f", brand, quantity, itemCost, getCost());
}
于 2013-10-05T19:04:45.117 回答
0

你的代码对我来说看起来不错。要在 toString() 方法中调用 getCost(),只需使用 getCost() 调用即可。

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

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

    return s;
}

希望这就是你要找的:)

于 2013-10-04T02:00:16.700 回答
0

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

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

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

您可能还想看一下NumberFormat,这将允许您控制输出格式,以防万一您得到一个有趣的值;)

于 2013-10-04T02:00:23.907 回答