user3705481 user3705481 - 2 months ago 37
Java Question

java.lang.ArrayIndexOutOfBoundsException: 5

I'm adding two arrays of the same length and I've written the code for it and no compile error shows up but when I run it I get:


java.lang.ArrayIndexOutOfBoundsException: 5


public class sumArray {
static double[] data1= {1.2, 2.3, 3.4, 5.1, 7.8};
static double[] data2= {5.3, 7.9, 2.1, 6.4, 9.2};
public static void main(String[] args){
sumArray();
}

public static double [] sumArray(){
double[] data3 = new double[data1.length];
for(int i = 0; i <= data1.length; i++){
data3[i] = data1[i] + data2[i];
}
return data3;
}
}

Answer

You're comparing from 0 - 5 (i.e. 6 elements, but your array has only 5), so you're going out of the bounds.

All you have to do is to go from 0 - data1.length - 1 like:

Change

for (int i = 0; i <= data1.length; i++){
     data3[i] = data1[i] + data2[i];

}

to

for (int i = 0; i < data1.length; i++){
     data3[i] = data1[i] + data2[i];
}

or change it to:

for (int i = 0; i <= (data1.length - 1); i++){
     data3[i] = data1[i] + data2[i];

}
Comments