Java Arraylist程序
我做了一个程序,但输出显示Java Arraylist程序,java,Java,我做了一个程序,但输出显示0。你能看出我做错了什么吗? 我的评估说明要求这样做 package snippet; import java.util.ArrayList; public class CO2FromElectricity { // declaration of private instance variables /** * Default constructor to create an object from the CO2FromElectric
0
。你能看出我做错了什么吗?
我的评估说明要求这样做
package snippet;
import java.util.ArrayList;
public class CO2FromElectricity {
// declaration of private instance variables
/**
* Default constructor to create an object from the CO2FromElectricity class.
*/
CO2FromElectricity() {
}
/**
* 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) {
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);
double sum = 0.0;
double monthlyTotal = 0.0;
for (int i = 0; i < monthlyBill.size(); i++) {
sum += monthlyBill.get(i);
}
return monthlyTotal / monthlyBill.size();
}
/**
* A mutator method which calculates the average annual price of electricity.
*
* @param monthlyPrice
* an ArrayList containing the monthly price of electricity per kilowatthour.
* @return the average monthly price of electricity.
*/
public double calcAveragePrice(ArrayList<Double> monthlyPrice) {
monthlyPrice.add(0.1117);
monthlyPrice.add(0.1107);
monthlyPrice.add(0.1110);
monthlyPrice.add(0.1113);
monthlyPrice.add(0.1135);
monthlyPrice.add(0.1138);
monthlyPrice.add(0.1217);
monthlyPrice.add(0.1215);
monthlyPrice.add(0.1216);
monthlyPrice.add(0.1228);
monthlyPrice.add(0.1209);
monthlyPrice.add(0.1192);
double sum = 0.0;
double monthlyTotal = 0.0;
for (int i = 0; i < monthlyPrice.size(); i++) {
sum += monthlyPrice.get(i);
}
return monthlyTotal / monthlyPrice.size();
}
/**
* A mutator method which calculates the annual home CO2 emission from electricity.
*
* @param avgBill
* the average monthly home electricity bill.
* @param avgPrice
* the average monthly price of home electricity.
* @return the annual home CO2 emission from home electricity use.
*/
public double calcElectricityCO2(double avgBill, double avgPrice) {
return (avgBill / avgPrice) * 1.37 * 12;
}
}
每月总计始终为0.0。因此,您的函数返回0.0/sum输出为0,因为您写入:
double monthlyTotal = 0.0;
我想你想
return sum/monthlyPrice.size();
您的输出方法在哪里?你做了大量的计算,但从来没有做过任何事情来显示它们。如何调用这些方法?看起来您提供了一个片段。这是您编写的完整代码吗?您没有提供调用此方法并执行输出的代码。我确实返回了(avgBill/avgPrice)*1.37*12;是这样吗?或者显示输出是我做错的部分?是的,这是我做的整个程序。这是一个问题,但我不确定OP在说输出为0时所指的是什么。由于没有调用输出方法,我猜0只是程序的返回代码。你完全正确。我以为在某个地方会有一份打印的声明,然后在数学上有了一个隧道式的视野。
return sum/monthlyPrice.size();