Sunday, April 27, 2014

Example of using Variable Length Arguments

Example to implement and call method with Variable Length Arguments.

package javavariablelengtharguments;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaVariableLengthArguments {

    public static void main(String[] args) {
        printAll(1, 2, 3, 4, 5, 6);
        System.out.println("average= " + average(1, 2, 3, 4, 5, 6));
    }
    
    static void printAll(int... num){
        for(int n : num){
            System.out.println(n);
        }
    }
    
    static float average(int... num){
        float total = 0;
        for(int i=0; i<num.length; i++){
            total+=num[i];
        }
        return total/num.length;
    }
    
}



No comments:

Post a Comment