gpt4 book ai didi

java - 尝试调用从另一个类定义变量的方法时出现编译错误

转载 作者:行者123 更新时间:2023-12-01 14:23:53 24 4
gpt4 key购买 nike

这两个类在 javdocs 中有深入描述,但简而言之:它旨在计算电力使用产生的二氧化碳排放量。但是,我在尝试编译时返回错误,内容如下:

non-static method calcAverageBill(java.util.ArrayList<java.lang.Double>) cannot be referenced from a static context.

我不确定是什么问题,有人可以帮忙吗?

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");
}
}

最佳答案

问题是 calcAverageBill 是一种对类型为 CO2fromElectricity 的对象进行操作的方法,但您调用它时就好像它是静态方法一样。也就是说,您必须在 CO2fromElectricity 实例上调用它,例如:

CO2fromElectricity inst = new CO2fromElectricity();
averageMonthlyBill = inst.calcAverageBill(monthlyBill);

或者,您可以通过在方法定义中添加 static 关键字来使方法静态化:

public static double calcAverageBill(ArrayList<Double> monthlyBill)

快速浏览一下 CO2fromElectricity,您可能希望定义的字段(例如 monthBillAverage)是每个方法中的局部变量,而不是作为字段或静态属性,因为您的类不会从实例范围或所有执行范围内定义这些受益(事实上,您可能会遇到当前定义它们的方式的一些麻烦)。

关于java - 尝试调用从另一个类定义变量的方法时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20938673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com