2D Array Traversal Error
What runtime error does the FlattenError program produce and why?
public class FlattenError {
public static int[] flatten(int[][] matrix) {
int count = 0;
for (int[] row : matrix) {
count += row.length;
}
int[] flat = new int[count];
int index = 0;
for (int i = 0; i < matrix.length; i++) {
// Error: Using '<=' causes index to go out of bounds
for (int j = 0; j <= matrix[i].length; j++) {
flat[index++] = matrix[i][j];
}
}
return flat;
}
public static void main(String[] args){
int[][] matrix = { {7,8,9}, {1,2,3} };
int[] flat = flatten(matrix);
for (int n : flat) System.out.print(n + " ");
}
}
A
NullPointerException because the matrix is not initialized properly.
B
The program prints an incorrect output but does not crash.
C
ArithmeticException due to division by zero in the loop counter.
D
ArrayIndexOutOfBoundsException, because the inner loop uses ‘j <= matrix[i].length’ instead of ‘j < matrix[i].length’.
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE