I am getting java.lang.ArrayIndexOutOfBoundsException: 5 when running this program.
public class TestArray {
public static void main(String[] args) {
int[] someArray = new int[5];
someArray[0] = 5;
someArray[1] = 10;
someArray[2] = 15;
someArray[3] = 20;
someArray[4] = 25;
System.out.println("Array length = " + someArray.length);
for (int i : someArray) {
System.out.println("Element at index " + i + ": " + someArray[i]);
}
}
}
Shouldn't the loop exit when i is greater than or equal to the length of the array which would be 5 in this case?
1 个答案:
答案 0 :(得分:5)
You are iterating over array values itself not the indexes. Use just i not someArray[i]
Or change your loop to
for (int i=0; i<someArray.length; i++)
Changing loop is better in this case based upon what you are trying to achieve there