I'm trying to design a program that creates an array and then populates it in one method, calculates the average in another method and then will print its contents and the average in the main method. However I get an incompatible type error when trying to pass the array to the calAverage method and do not understand why.
我正在尝试设计一个创建数组的程序,然后在一个方法中填充它,在另一个方法中计算平均值,然后在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 个解决方案
#1
1
The program shows the message: Incompatible types: int[] cannot be converted to int
.
程序显示消息:不兼容的类型:int []无法转换为int。
This is because the return type of the method calAverage()
is int[]
, i.e., it returns an integer array. But you want it to return an int
value as the variable average
in calAverage()
, whose value is returned, and the variable in the main method that gets its value assigned as the value returned by calAverage()
are of type int. So, change the return type of calAverage()
from int[]
to int
.
这是因为方法calAverage()的返回类型是int [],即它返回一个整数数组。但是你希望它返回一个int值作为calAverage()中的变量average,返回其值,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;
}
#1
1
The program shows the message: Incompatible types: int[] cannot be converted to int
.
程序显示消息:不兼容的类型:int []无法转换为int。
This is because the return type of the method calAverage()
is int[]
, i.e., it returns an integer array. But you want it to return an int
value as the variable average
in calAverage()
, whose value is returned, and the variable in the main method that gets its value assigned as the value returned by calAverage()
are of type int. So, change the return type of calAverage()
from int[]
to int
.
这是因为方法calAverage()的返回类型是int [],即它返回一个整数数组。但是你希望它返回一个int值作为calAverage()中的变量average,返回其值,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;
}