尝试从方法返回arraylist时出现“不兼容的类型”

时间:2013-12-19 14:11:07

标签: java arraylist

在这堂课中,我想要整体回归一个arraylist,而不是单独的元素。但是,我在编译时收到错误“不兼容的类型”。我在这做错了什么?感谢您的任何和所有帮助!!

import java.util.ArrayList;
public class CO2FromElectricity
{



/**
 * Constructor for objects of class CO2FromElectricity
 */
public CO2FromElectricity()
{

}

public static double calcAverageBill(ArrayList<Double> monthlyBill, int ind) 
{
  ArrayList<Double> avgBill = new ArrayList<Double>();
  int i = ind;
  avgBill.set(i, (monthlyBill.get(i) + avgBill.get(i))/2); 
  return avgBill.get(i);    
}

public double calcAveragePrice(ArrayList<Double> monthlyPrice, int ind)
{
    int i = ind; 
    ArrayList<Double> avgPrice = new ArrayList<Double>();
    avgPrice.set(i, (monthlyPrice.get(i) + avgPrice.get(i))/2);
    return avgPrice;
}

public double calcElectricityCO2(double avgBill, double avgPrice)
{
    double avBill = avgBill;
    double avPrice = avgPrice; //Price per kilowatt that is...
    double emissions = (avBill/avPrice)*1.37*12; 
    return emissions;

}
}

5 个答案:

答案 0 :(得分:4)

calcAveragePrice()方法中,您返回List,而该方法定义为返回double

将方法签名更改为

public List<Double> calcAveragePrice(...)

返回double

return list.get(i); //similar to the getAverageBill() method

答案 1 :(得分:2)

public double calcAveragePrice(ArrayList<Double> monthlyPrice, int ind)

该方法需要返回一个double。

ArrayList<Double> avgPriAce = new ArrayList<Double>();
...
return avgPrice;

您正在返回一个arrayList。将您的代码更改为:

public ArrayList<Double> calcAveragePrice(ArrayList<Double> monthlyPrice, int ind)

这应该解决它。


第二个想法,你的方法正在做一些非常奇怪的事情。我相信你不想要一个arraylist作为一个平均值。你绝对想要一个双倍的平均值。

如果我的假设是正确的,那么您是在尝试将monthPrice中的每个值相加并返回平均值?在这种情况下,您需要遍历数组中的每个值并将它们相加并除以元素数量以获得平均值并将其作为double返回。我的2美分。

答案 2 :(得分:1)

public ArrayList<Double> calcAveragePrice(ArrayList<Double> monthlyPrice, int ind) {
    int i = ind;
    ArrayList<Double> avgPrice = new ArrayList<Double>();
    avgPrice.set(i, (monthlyPrice.get(i) + avgPrice.get(i)) / 2);
    return avgPrice;
}

答案 3 :(得分:1)

您的calcAveragePrice正在返回一个List(正如其他已经提到的那样)。

但它也没有任何意义。您创建大小为0的列表,但之后您尝试在不存在的索引处设置列表(因为列表为空)然后返回它。这个函数即使你修复它所以它编译也会抛出一个IndexOutOfBoundsException,除非ind是0。

如果你想要一个你需要正确使用它的列表,你很可能根本就不想要一个列表。

答案 4 :(得分:0)

public double calcAveragePrice(ArrayList<Double> monthlyPrice, int ind){ 
// return type is double    
int i = ind; 
ArrayList<Double> avgPriAce = new ArrayList<Double>();
avgPrice.set(i, (monthlyPrice.get(i) + avgPrice.get(i))/2);
return avgPrice; // you are returning  a list. This is Incompatible
 }

更改代码,以达到您想要的效果I'm wanting to return an arraylist in whole, not as individual elements

public List<Double> calcAveragePrice(ArrayList<Double> monthlyPrice,int ind){  
List<Double> avgPrice = new ArrayList<Double>();
// your implementation 
return avgPrice; // you are returning  a list
}
相关问题