简体   繁体   English

Java中多重参数对我不起作用

[英]multiple argument isn't working for me in Java

I am trying run this code but its not working for me to get multiple arguments. 我正在尝试运行此代码,但对我来说,获取多个参数不起作用。

public class apples {


public static void main (String []args) {
    System.out.println( average(43,56,76,4,32,3));
}
    public static int average(int...numbers){
        int total = 0;
        for (int x:numbers){
            total +=x;
            return total/numbers.length;
        }
  }

 }

you want return statement 您要return声明

return total/numbers.length;

out of loop 跳出循环

You need to put the return statement outside the for loop: 您需要将return语句放在for循环之外:

public static int average(int... numbers)
{
    int total = 0;
    for (int x : numbers) {
        total += x;

    }
    return total / numbers.length;
}

This is because if you pass 0 arguments to the method average() you won't never enter the body of the for loop. 这是因为如果将0参数传递给方法average() ,则永远不会输入for循环的主体。 So the method won't reach a return statement. 因此该方法将不会return语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM