对于参数类型String,void,未定义operator +

public class chap7p4 { public static void main(String[] args) { int[] heights = { 33, 45, 23, 43, 48, 32, 35, 46, 48, 39, 41, }; printArray(heights); System.out.println("Average is " + findAverage(heights)); // this is where I get the error } public static void printArray(int[] array) { for (int eachNum : array) { System.out.println(eachNum + " "); } } public static void findAverage(int[] array) { int average = 0; int total = 0; for (int i = 0; i <= array.length; i++) { total = total + array[i]; } average = total / array.length; System.out.println(average); } } 

我收到这个错误

 "Exception in thread "main" java.lang.Error: Unresolved compilation problem: The operator + is undefined for the argument type(s) String, void" 

findAverage具有void返回类型。 更改方法的返回类型以返回int

 public static int findAverage(int[] array) { ... return total / array.length; } 

您的方法findAverage(heights)必须返回一个值才能应用于二元运算符+ ,它需要两个操作符。

你做不到

String + void

findAverage方法返回void

更改findAverage()方法的返回类型,

void findAverageint findAverage void findAverage

 public static int findAverage(int[] array) { int total = 0; for (int i = 0; i <= array.length; i++) { total = total + array[i]; } return total / array.length; } 

findAverage方法的Return类型不应该为void,它应该是代码的整数。 您不应该使用与在main方法中调用的方法相同的方法打印average的值。

此处参数的类型为int,而类似(*,+,..)的运算符不适用于参数类型void和int,因此如上所述更改参数类型或返回类型。