First, let's address a bug in your code. Consider this loop:
int i;
for (i = 0; i < 10; i++) { /* loop body */ }
The loop runs until i < 10
evaluates to false
. In this example, when the loop exits, i
will have a value of 10
.
Consider the inner loop in your code:
for (currentRow = 0; currentRow < array2d.length; currentRow++)
When this loop exits, currentRow
will be equal to array2d.length
. Then, control will return to the outer loop. When it does, in the control expression currentColumn < (array2d[currentRow].length)
, this part array2d[currentRow]
will throw an IndexOutOfBoundsException
.
As you already know, here is the standard way of going through a 2D array in row by column order is like this:
for (int row = 0; row < array2d.length; row++) {
for (int column = 0; column < array2d[row].length; column++ {
// things to do in inner loop
}
If you wanted to process a rectangular 2D array in column order, the code might look like this:
for (int column = 0; column < array2d[0].length; column++) {
for (int row = 0; row < array2d.length; row++) {
// loop body
}
}
But, what if the array is ragged?
Start by finding the row with the maximum number of columns at the start:
int maxColumns = 0;
for (int i = 0; i < array.length; i++) {
maxColumns = Math.max (maxColumns, array2d[i].length);
}
Then, your code might look something like this:
for (int column = 0; column < maxColumns; column++) {
for (int row = 0; row < array2d.length; row++) {
if (column < array2d[row].length) {
// do something with array2d [row][column]
} else {
// do something for the case where
// array2d [row] doesn't have a value in "column"
}
}
}
An alternative might be to try to trap an ArrayIndexOutOfBoundsException
. However, that might be regarded as a poor programming practice.