java optional parameters [duplicate]

假装没事ソ 提交于 2019-12-05 18:01:21

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

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

}

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;

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!