Are you taking CLEP classes? Try clep.ai
| preferred AP College board partner for AP classes
AP Computer Science A/Unit 8: 2D Array
Start Practice TestPractice Test
About Exam
medium

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
Report Question
Mark for review

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|