BlazeRyder BlazeRyder - 1 month ago 18
Java Question

Multidimensional arrays.

I am doing a project for school that deals with Arrays and I have run into a problem! I was wondering if anybody could help me out and explain the error that I am getting! So here is my code:

public class ArrayPrinter
{
public static void main(String[] args)
{
int [] oneD = {5, 6, 7, 8 };

int[][] twoD = {{2, 4, 6, 8},
{8, 7, 9, 1},
{3, 5, 1, 2}};

int[][] twoD2 = {{1, 2},
{3, 4, 5},
{6},
{7, 8, 9}};

printArray(oneD);

printArray(twoD);

System.out.println(" ");

printArray(twoD2);
}


public static void printArray(int[] arr) {

int size = arr.length;
System.out.print("[");
for(int i=0;i< size; i++){
System.out.print(arr[i]);
if(i<size-1){
System.out.print(",");
}
}
System.out.println("]");
}

public static void printArray(int[][] arr)
{

System.out.println("[ ");

for (int row = 0; row < arr.length; row++){

System.out.print("");

for (int i = 0; row < arr[row].length; i++)
{
printArray(arr[i]);

}
System.out.println("]");

}
}
}


I am getting an error when I run this in Eclipse. This is my output:

[5,6,7,8]

[

[2,4,6,8]

[8,7,9,1]

[3,5,1,2]

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at ArrayPrinter.printArray(ArrayPrinter.java:51)

at ArrayPrinter.main(ArrayPrinter.java:19)

How can I fix this error? And could you please explain why and not just do it for me? I e-mailed my teacher but she is not responding and I have to get this done. Thanks in advance to anyone who helps me!!!!!

Answer

Think about what you're doing in printArray(int[][] arr):

for (int row = 0; row < arr.length; row++){
    ...
}

This loops over the rows of the array. Remember, all those rows are arrays. At this point, arr[row] has type int[]. You have a printArray function that accepts an int[], so call that. The part where you loop over i is unnecessary.

Your IndexOutOfBoundsException occurs when you try to access an element of an array that is out of bounds. For example:

int[] arr = {42};
arr[3] // IndexOutOfBoundsException! arr has length 1, so arr[3] is out of bounds

You are getting the error because you are trying to loop over i, but the condition for termination is row < arr[row].length. That means that on the first iteration row will be 0. It will enter the i loop, and it will check if 0 < twoD2[0].length (it is) and then it will access twoD2[i]. Then it increments i and performs the check again, but row has not been updated! If a condition is true at the entry of a loop and you don't change the variables that are used in the condition, you will never exit the loop. Thus i never stops incrementing and eventually you try to access twoD2[4] and get the exception.

Comments