Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java optional parameters [duplicate]

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

like image 910
Hellnar Avatar asked Dec 01 '22 06:12

Hellnar


2 Answers

Java 5 supports varargs, which is what you want.

e.g.

public static int average(Integer... ints) {
   for (Integer i : ints) {
       // sum here...
   }
}
like image 133
Brian Agnew Avatar answered Dec 05 '22 17:12

Brian Agnew


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));
}
like image 38
coobird Avatar answered Dec 05 '22 17:12

coobird