一尘不染

未为参数类型定义运算符+字符串,无效

java

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"

阅读 179

收藏
2020-12-03

共1个答案

一尘不染

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

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