Passing an unknown number of variables to a method

Sometimes you want to build a method and you don’t know how many arguments it needs. For example, a method that averages a bunch of numbers. This example shows how to build a method that takes as many arguments as you want.

class jamesprogram {

	public static void main(String args[]){
	
		System.out.println(average(1,2,3,4));
		
	}
	
	// the 3 dots is an ellipse, this tells the program
	// that you are going to put in an unknown bunch
	// of numbers of type int
	public static double average (int...numbers){
		
		double total=0;
		for (double x:numbers){
			total+=x;
		}
			
		return total/numbers.length;
			
	}
}

Outputs:

2.5

Leave a Reply