0

I know questions about this error have been asked before but my situation is different from all the other ones. I am writing code that comes up with the mean, variance, and standard deviation of a data set. I don't get any errors when compiling the code but when I try to run the code I get an error like this : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Main.main(Main.java:25)

/**   
 * Main class of the Java program. 
 * 
 */

public class Main {

    public static void main(String[] args) {
        int sum = 0;
        double xBar = 0;
        double [] dataSet = {1,2,3,4}; // add data here
        int xLenght = dataSet.length;
        double [] diffrenceSquared={};
        double devSum = 0;
        double variance = 0;
        double standardDeviation = 0;
         for (double n: dataSet)
         {
            sum += n;    
         }
          xBar = sum/xLenght;

          for (int i=0; i<dataSet.length; i++)
          {
            diffrenceSquared[i] = (xBar-dataSet[i])*(xBar-dataSet[i]);
          } 
          for (double n:dataSet)
        {
              devSum += n;
        }    
        variance = devSum/xLenght;

        standardDeviation = java.lang.Math.sqrt(variance);
        System.out.println("x bar ="+xBar);
        System.out.println("variance ="+ variance);
        System.out.println("Standard Deviation ="+ standardDeviation);
    }
}

Please help me!

2 Answers2

2

You have declared diffrenceSquared to be a zero-length array with this declaration:

double [] diffrenceSquared={};

That means that there are no elements to assign, and every index is out of bounds.

You're attempting to assign elements to diffrenceSquared in a loop bounded by dataSet's length, so instead declare it to be that length.

double[] diffrenceSquared = new double[dataSet.length];
rgettman
  • 176,041
  • 30
  • 275
  • 357
0
double [] diffrenceSquared = new double[dataSet.length];

In Java, arrays are not resizable, so you have to give them the right size from the start.

Alternatively, you can use Lists, which are more flexible.

Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51