Question: Write a method that takes as input a variable number of integers. The method should return the average of the integers as a double. Write a full program to test the method.
That code below creates an array of 10 integers and finds their average. However, I need it to create a variable number of arguments (int...a) where any number of integers entered can be averaged. Can someone help me.Thanks.
My code:
package average.pkgint;
import java.util.Scanner;
public class AverageInt {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int [] number = new int [10];
Scanner b = new Scanner(System.in);
System.out.println("Enter your 10 numbers:");
for (int i = 0; i < number.length; i++) {
number[i] = b.nextInt() ;
}
System.out.println("The average is:"+Avnt(number));
}
public static int Avnt(int [] a){//declare arrays of ints
int result = 1;
int sum = 0;
//iterate through array
for (int num : a) {
sum += num;
}
double average = ( sum / a.length);//calculate average of elements in array
result = (int)average;
return result;
}
}
intas type ofsum. You can make that overflow with just 2 ints (Integer.MAX_VALUE + 1 == Integer.MIN_VALUE). Use long or double instead.