1
1
package com .thealgorithms .maths ;
2
2
3
3
/**
4
- * Utility class for calculating the average of a list of numbers .
4
+ * Utility class for calculating the average of numeric arrays .
5
5
*/
6
6
public final class Average {
7
7
8
8
// Private constructor to prevent instantiation
9
9
private Average () {
10
- throw new UnsupportedOperationException ("Utility class cannot be instantiated" );
11
10
}
12
11
13
12
/**
14
13
* Calculates the average of a double array.
15
14
*
16
- * @param numbers the array of numbers
15
+ * @param numbers an array of doubles
17
16
* @return the mean of the given numbers
18
- * @throws IllegalArgumentException if the input array is null or empty
17
+ * @throws IllegalArgumentException if the array is null or empty
19
18
*/
20
- public static double average (double [] numbers ) {
21
- validateInput (numbers );
19
+ public static double calculateAverage (double [] numbers ) {
20
+ if (numbers == null || numbers .length == 0 ) {
21
+ throw new IllegalArgumentException ("Array cannot be null or empty." );
22
+ }
22
23
double sum = 0 ;
23
24
for (double number : numbers ) {
24
25
sum += number ;
@@ -29,28 +30,18 @@ public static double average(double[] numbers) {
29
30
/**
30
31
* Calculates the average of an int array.
31
32
*
32
- * @param numbers the array of numbers, ensuring the sum does not exceed long value limits
33
- * @return the average value
34
- * @throws IllegalArgumentException if the input array is null or empty
33
+ * @param numbers an array of integers
34
+ * @return the mean of the given numbers
35
+ * @throws IllegalArgumentException if the array is null or empty
35
36
*/
36
- public static int average (int [] numbers ) {
37
- validateInput (numbers );
37
+ public static int calculateAverage (int [] numbers ) {
38
+ if (numbers == null || numbers .length == 0 ) {
39
+ throw new IllegalArgumentException ("Array cannot be null or empty." );
40
+ }
38
41
long sum = 0 ;
39
42
for (int number : numbers ) {
40
43
sum += number ;
41
44
}
42
45
return (int ) (sum / numbers .length );
43
46
}
44
-
45
- /**
46
- * Validates the input array.
47
- *
48
- * @param numbers the array of numbers
49
- * @throws IllegalArgumentException if the input array is null or empty
50
- */
51
- private static void validateInput (Object numbers ) {
52
- if (numbers == null || ((Object []) numbers ).length == 0 ) {
53
- throw new IllegalArgumentException ("Numbers array cannot be null or empty" );
54
- }
55
- }
56
47
}
0 commit comments