开发者

java optional parameters [duplicate]

开发者 https://www.devze.com 2022-12-11 17:16 出处:网络
This question alread开发者_JS百科y has answers here: How do I use optional parameters in Java? (17 answers)
This question alread开发者_JS百科y has answers here: How do I use optional parameters in Java? (17 answers) Closed 3 years ago.

I want to write an average method in java such that it can consume N amount of items, returning the average of them:

My idea was:

    public static int average(int[] args){
        int total = 0;
        for(int i=0;i<args.length;i++){
            total = total + args[i];
        }
        return Math.round (total/args.length);
    }
//test it
average(1,2,3) // s**hould return 2.

how can I change my method to consume any amount of parameters instead of int[] args so can work the way I want ? Cheers


Java 5 supports varargs, which is what you want.

e.g.

public static int average(Integer... ints) {
   for (Integer i : ints) {
       // sum here...
   }
}


Since Java 5, there is a feature commonly called varargs which achieves what is desired.

Here's a little example:

public static int add(int... nums) {
    int total = 0;

    for (int n : nums)
        total += n;

    return total;
}

public static void main(String[] s) {
    // The following prints "10"
    System.out.println(add(1, 2, 3, 4));
}


function average() {

var total = 0;

if(arguments.length > 0) {

 for(var i = 0, n = arguments.length; i < n; i++) {

  total += parseFloat(arguments[i]);

 }

 total /= arguments.length;

}

return total;

}


Here's the optional arguments version (almost no code changes...)

public class Spike2 {

  public static final void main(String argv[]) {
    System.out.println(average(1,2,3));
  }

   public static int average(int... args){
        int total = 0;
        for(int i=0;i<args.length;i++){
                total = total + args[i];
        }
        return Math.round (total/args.length);
    }

}

with iterator changes:

public class Spike2 {

  public static final void main(String argv[]) {
    System.out.println(average(1,2,3));
  }

   public static int average(int... args){
        int total = 0;
        for(int i:  args){
                total = total + i;
        }
        return Math.round (total/args.length);
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号