这两个类在javdocs中有详细描述,但简而言之:它用于计算用电量的二氧化碳排放量。但是,我在尝试编译时返回错误,如下所示:
非静态方法
calcAverageBill
(java.util.ArrayList<java.lang.Double>
)无法从静态上下文中引用。
我不确定问题是什么,有人可以帮忙吗?
public class CO2fromElectricity
{
private double monthBillAverage;
private double monthPriceAverage;
private double annualCO2emission;
private double emissionFactor;
private double months;
CO2fromElectricity() { }
public double calcAverageBill(ArrayList<Double> monthlyBill)
{
monthBillAverage = 0;
for(double billToken : monthlyBill)
{
monthBillAverage += billToken;
}
return monthBillAverage / monthlyBill.size();
}
public double calcAveragePrice(ArrayList<Double> monthlyPrice)
{
monthPriceAverage = 0;
for(double billToken : monthlyPrice)
{
monthPriceAverage += billToken;
}
return monthPriceAverage / monthlyPrice.size();
}
public double calcElectricityCO2(double avgBill, double avgPrice)
{
emissionFactor = 1.37;
months = 12;
return annualCO2emission = avgBill / avgPrice * emissionFactor * months;
}
}
public class CO2fromElectricityTester
{
public static void main(String[] args)
{
ArrayList<Double> monthlyBill = new ArrayList<Double>();
ArrayList<Double> monthlyPrice = new ArrayList<Double>();
double averageMonthlyBill,
averageMonthlyPrice,
annualCO2emission;
double monthlyBillToken1[] = {192.14, 210.42, 231.25, 186.13},
monthlyPriceToken1[] = {.07, .06, .08, .06};
for(int index = 0; index < monthlyBillToken1.length; index++)
{
monthlyBill.add(monthlyBillToken1[index]);
monthlyPrice.add(monthlyPriceToken1[index]);
}
ArrayList<CO2FootprintV1> electricCO2outputput = new ArrayList<CO2FootprintV1>();
averageMonthlyBill = CO2fromElectricity.calcAverageBill(monthlyBill);
averageMonthlyPrice = CO2fromElectricity.calcAveragePrice(monthlyPrice);
annualCO2emission = CO2fromElectricity.calcElectricityCO2(averageMonthlyBill, averageMonthlyPrice);
System.out.println("Average Monthly Electricity Bill: " + averageMonthlyBill);
System.out.println("Average Monthly Electricity Prince: " + averageMonthlyPrice);
System.out.println("Annual CO2 Emissions from Electricity Useage: " + annualCO2emission + "pounds");
}
}
答案 0 :(得分:3)
问题是calcAverageBill
是一种对类型为CO2fromElectricity
的对象进行操作的方法,但您将其称为静态方法。也就是说,您必须在CO2fromElectricity
的实例上调用它,例如:
CO2fromElectricity inst = new CO2fromElectricity();
averageMonthlyBill = inst.calcAverageBill(monthlyBill);
或者,您可以通过将static关键字添加到方法定义中来使方法保持静态:
public static double calcAverageBill(ArrayList<Double> monthlyBill)
快速查看CO2fromElectricity
您可能希望您定义的字段(例如monthBillAverage
)是每个方法中的局部变量而不是字段或静态属性,因为您的类没有'从在实例范围内或在所有执行范围内定义这些内容中受益(实际上,您可能会遇到它们当前定义的方式)。