| preferred AP College board partner for AP classes
AP Computer Science A/Unit 8: 2D Array
Start Practice TestPractice Test
Share
About Exam
medium Solved by 2 students
2D Array Traversal Error
< Prev
Next >

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’.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer

Question Leaderboard

Not enough data yet to show leaderboard.

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy