在java中调用方法并返回啤酒成本 [英] Calling a method in java and returning beer cost

查看:89
本文介绍了在java中调用方法并返回啤酒成本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该做什么:


printOrderCost()主类中的c $ c>方法,以便此方法计算并打印订单中所有啤酒项目的总成本
。 (此方法为每个啤酒项调用 getCost()方法
,累计所有 getCost()
值,然后打印总和 - 所有啤酒对象的总成本。)

Add some necessary statements to the printOrderCost() method in the main class so that this method computes and prints the total cost of all beer items in the order. (This method calls the getCost() method for each beer item, accumulates the sum of all of the getCost() values, and then prints the sum – the total cost of all beer objects.)

代码:

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


推荐答案

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

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(...).

示例:

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

这篇关于在java中调用方法并返回啤酒成本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆