0

Need help running this code, I need to find the error so I can fix it. Thanks! the error receive is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at DebuggingExercise.main(DebuggingExercise.java:13)

    import java.io.*;


    public class DebuggingExercise {

    public static void main(String[] args)
    {
        int[][] testArray = new int[5][6];

        for(int i=0;i<5;i++)
        {
            for(int j=1; j<=6; j++)
                testArray[i][j] = (i+1)*j;
        }
    }



}
Steak
  • 15
  • 2

2 Answers2

3

In this for loop:

for(int j=1; j<=6; j++)
    testArray[i][j] = (i+1)*j;

"6" is out of the index of the array of size "6" (0 - 5).

4dc0
  • 453
  • 3
  • 11
3

Welcome to StackOverflow. Let's explain this step by step:

int[][] testArray = new int[5][6];

means a two dimensional array with 5 rows and 6 columns. Array's index start from 0. So 5 rows will be given indices like; 0,1,2,3,4

And each row will contain 6 columns that means, 0,1,2,3,4,5

for(int i=0;i<5;i++)

means start from 0 and go until 4 because when i's value becomes 5, this will finish this loop. That's okay, since you are using i to refer to the row index. So 0,1,2,3,4 for rows will be fine in this case.

for(int j=1; j<=6; j++)

That means, start from 1 and go until 6. Since you are referring the array's column with j, it will be like following when value of i is 0.

testArray[0][1]

testArray[0][2]

testArray[0][3]

testArray[0][4]

testArray[0][5]

testArray[0][6] //Here is the exception since each row has only 6 columns and array index starts with 0 that is: 0,1,2,3,4,5

Hence you receive ArrayIndexOutOfBoundException

Community
  • 1
  • 1
SSC
  • 2,956
  • 3
  • 27
  • 43