根本不知道如何解决这个错误。尝试使用Array列表创建平均值。第二个代码列表是(tester main [])。如您所见,已创建ArrayList和数组值。 (不知道是否有单独的arraylist和数组标记,所以我在两者中发帖。)
**
* A mutator method which calculates the average annual electricity bill.
* @param monthlyBill an ArrayList containing the monthly bills for home electricity use.
* @return the average monthly electricity bill.
*/
public double calcAverageBill(ArrayList<Double> monthlyBill)
{
double sum=0;
if (!monthlyBill.isEmpty())
{
for (double month: monthlyBill )
{
sum+=month;
}
return (sum.doubleValue())/ monthlyBill.size();
}
}
public static void main(String[ ] args)
{
CO2FromElectricity CO2 = new CO2FromElectricity();
ArrayList<Double> monthlyBill = new ArrayList<Double>();
monthlyBill.add(279.41);
monthlyBill.add(238.03);
monthlyBill.add(248.64);
monthlyBill.add(258.73);
monthlyBill.add(395.48);
monthlyBill.add(419.91);
monthlyBill.add(431.15);
monthlyBill.add(407.56);
monthlyBill.add(417.14);
monthlyBill.add(308.35);
monthlyBill.add(337.91);
monthlyBill.add(320.77);
答案 0 :(得分:2)
你错过了一个大括号(你没有关闭if
),而你的sum.doubleValue()
不正确(因为sum
已经是原始的“双”)。
public double calcAverageBill(java.util.List<Double> monthlyBill) {
double sum = 0;
if (!monthlyBill.isEmpty()) {
for (double month : monthlyBill) {
sum += month;
}
}
return (sum / monthlyBill.size());
}
答案 1 :(得分:2)
最简单的形式就是
// generic method to calculate an average of an Iterable/List of Double.
public static double average(Iterable<Double> nums) {
double sum = 0;
for (double d : nums)
sum += d;
return sum / nums.size();
}
答案 2 :(得分:1)