Varargs Average of Doubles in Java
Write a Java program demonstrating a method with varargs that returns the average of a set of doubles
- The class AverageCalculator contains a single static method calculateAverage that takes a variable number of double values as input (using varargs).
- Inside the calculateAverage method, it first checks if the length of the numbers array is zero. If so, it throws an IllegalArgumentException with the message "No numbers provided".
- It then initializes a variable sum to zero to store the sum of the numbers.
- It iterates through each number in the numbers array and adds it to the sum.
- After adding all the numbers, it calculates the average by dividing the sum by the length of the numbers array and returns the result.
- In the main method, the calculateAverage method is called with several double values. The calculated average is then printed to the console.
Source Code
public class AverageCalculator
{
static double calculateAverage(double... numbers)
{
if (numbers.length == 0)
{
throw new IllegalArgumentException("No numbers provided");
}
double sum = 0;
for (double num : numbers)
{
sum += num;
}
return sum / numbers.length;
}
public static void main(String[] args)
{
double average = calculateAverage(10.5, 5.3, 7.8, 12.1);
System.out.println("Average: " + average);
}
}
Output
Average: 8.925