ZeldaX - 3 months ago 15

Java Question

I am trying to add a given 3D array and print it as D. Moreover, I have to take the array[0] and [1] from a given 3d Array and add their corresponding positions in a 2D Array an add them.

For example, if a 3D Array has the following 2D Matrices

`> Array[0] : {1,2,3},`

>

> {4,5,6}

>

>

> Array[1] : {1,1,1},

>

> {1,1,1}

The 2D Array should print

`{2,3,4},`

>

> {5,6,7}

This is my code. However, it gives the following error:

`Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2`

at ThreeDRay.add(ThreeDRay.java:53)

at ThreeDRayRunner.main(ThreeDRayRunner.java:53)

Line 53 is:

`for (int j=0; j<b[j].length;j++)`

but I dont know whats wrong with it

`public static void add(int[][][]array)`

{

int [][] b = new int[array[0].length][array[0][0].length];

for (int x=0; x<array.length;x++)

{

for (int y=0; y<array[0].length;y++)

{

for (int z=0; z<array[0][0].length;z++)

{

b[y][z] += array[x][y][z];

}

}

}

System.out.println ("Adding matrix at 0 and matrix at 1 ");

for (int i=0; i<b.length;i++)

{

for (int j=0; j<b[j].length;j++)

{

System.out.print(b[i][j]);

}

System.out.println();

}

}

}

Answer

```
for (int j=0; j<b[j].length;j++)
{
System.out.print(b[i][j]);
}
```

Here you are taking `b[j]`

length which can potentially go out of bounds, because you are taking different array later (`b[i]`

). Just do `b[i].length`

in that `for`

loop and it should fix it. Remember that `for`

loop is checking the condition before every iteration, not just at creation.