Skip to content

Update Average.java #5309

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions src/main/java/com/thealgorithms/maths/Average.java
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
package com.thealgorithms.maths;

/**
* Calculate average of a list of numbers
* A utility class for computing the average of numeric arrays.
* This class provides static methods to calculate the average of arrays
* of both {@code double} and {@code int} values.
*/
public final class Average {

// Prevent instantiation of this utility class
private Average() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated.");
}

/**
* Calculate average of a list of numbers
* Computes the average of a {@code double} array.
*
* @param numbers array to store numbers
* @return mean of given numbers
* @param numbers an array of {@code double} values
* @return the average of the given numbers
* @throws IllegalArgumentException if the input array is {@code null} or empty
*/
public static double average(double[] numbers) {
if (numbers == null || numbers.length == 0) {
Expand All @@ -25,20 +31,20 @@ public static double average(double[] numbers) {
}

/**
* find average value of an int array
* Computes the average of an {@code int} array.
*
* @param numbers the array contains element and the sum does not excess long
* value limit
* @return average value
* @param numbers an array of {@code int} values
* @return the average of the given numbers
* @throws IllegalArgumentException if the input array is {@code null} or empty
*/
public static int average(int[] numbers) {
public static double average(int[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Numbers array cannot be empty or null");
}
long sum = 0;
for (int number : numbers) {
sum += number;
}
return (int) (sum / numbers.length);
return (double) (sum / numbers.length);
}
}