Java 参数类型的运算符 + 未定义 String, void

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22910467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:53:37  来源:igfitidea点击:

The operator + is undefined for the argument type(s) String, void

javacompiler-errors

提问by NedNarb

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);

    }
}

I get this error

我收到这个错误

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

采纳答案by Reimeus

findAveragehas a void return type. Change the return type for the method to return an intvalue

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

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

回答by Harmlezz

Your method findAverage(heights)has to return a value to be applicaable for the binary operator +, which takes two operants.

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

回答by Harshal Patil

Change return type of your findAverage()method,

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

i.e void findAverageto int findAverage

void findAverageint 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;
}

回答by gstackoverflow

you cannot make

你不能做

String+ void

String+ void

findAveragemethod returns void

findAverage方法返回 void

回答by gstackoverflow

Returntype of findAveragemethod should not be void it should be integer for your code. You should not print the value of average in same method as you are calling in main method.

ReturnfindAverage方法类型不应该是 void 它应该是你的代码的整数。您不应该在与在 main 方法中调用相同的方法中打印平均值的值。

回答by user8127513

Also here argument is of type int, and Operators like(*,+,..) won't work for argument type void and int so either change argument type or return type as mentioned above.

此外,这里的参数是 int 类型的,并且像 (*,+,..) 这样的运算符不适用于参数类型 void 和 int,因此如上所述更改参数类型或返回类型。