I'm trying to create a Java program to calculate the mean and standard deviation for an array of values. The program compiles just fine. However, I get an ArrayIndexOutofBoundException error after entering the values for arr.
It says the error is within the computeMean method but I just can't find the mistake as (i < arr.length) should not exceed the boundaries of the array.
Any help would be greatly appreciated!
// This program computes the mean and standard deviation
// of an array of values.
import java.util.Scanner;
public class Statistics {
public static void main(String[] args) {
double mean, deviation;
int[] arr = readArray();
arr = new int[arr.length];
mean = computeMean(arr);
deviation = computeStdDev(arr);
System.out.printf("Mean = %.3f\n", mean);
System.out.printf("Standard deviation = %.3f\n", deviation);
}
// Read a list of values into an array arr
public static int[] readArray() {
int i, size;
Scanner sc = new Scanner(System.in);
System.out.print("Enter size of array: ");
size = sc.nextInt();
if(size == 1)
System.out.println("Enter " + size + " value:");
else
System.out.println("Enter " + size + " values:");
int[] array = new int[size];
for(i = 0; i < size; i++)
array[i] = sc.nextInt();
return array;
}
// Compute mean of the values in arr
// Precond: arr.length > 0
public static double computeMean(int[] arr) {
int i, sum = 0;
double mean;
for(i = 0; i < arr.length; i++);
sum += arr[i];
mean = sum/arr.length;
return mean;
}
// Compute standard deviation of the values in arr
// Precond: arr.length > 0
public static double computeStdDev(int[] arr) {
int i;
double variance, deviation, total = 0;
for(i = 0; i < arr.length; i++)
total += Math.pow((arr[i] - computeMean(arr)), 2);
variance = total/arr.length;
deviation = Math.sqrt(variance);
return deviation;
}
// Print the array arr on a single line.
// Note that the last element has a space after it.
public static void printArray(int[] arr) {
for (int element: arr) {
System.out.print(element + " ");
}
System.out.println();
}
}