试图将数组传递给方法但抛出不兼容的类型错误?

时间:2016-08-07 09:26:48

标签: java arrays incompatibletypeerror

我正在尝试设计一个创建数组的程序,然后在一个方法中填充它,在另一个方法中计算平均值,然后在main方法中打印其内容和平均值。但是,当尝试将数组传递给calAverage方法并且不理解原因时,我收到了不兼容的类型错误。

public class week3d
{
    public static void main (String [] args)
    {
    int [] list = new int [20];
    list = fillArray();
    int average = calAverage(list); // this is where the error occurs


    System.out.println("The average of this list is "+average/20);
}

public static int [] fillArray()
    {
    int [] a = new int[20];
    for (int i =0;i <20;i++)
    {
    a[i] = i*10;
    System.out.println(a[i]);
    }    
    return a;
}

public static int [] calAverage(int[] a)
{
    int average = 0;
    for (int i =0;i <20;i++)
    {
    average += a[i];
    }   
    return average / 20;
    }
}

1 个答案:

答案 0 :(得分:1)

该程序显示消息:Incompatible types: int[] cannot be converted to int

这是因为方法calAverage()的返回类型是int[],即它返回一个整数数组。但是,您希望它返回int值作为average中的变量calAverage(),其值将被返回,而main方法中的变量将其值指定为返回的值calAverage()的类型为int。因此,请将calAverage()的返回类型从int[]更改为int

public static int calAverage(int[] a)
{
    int average = 0;
    for (int i =0;i <20;i++)
    {
        average += a[i];
    }   
    return average / 20;

}