You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

带条件打印NxN数组的代码抛出"Exception in thread 'main'"异常,如何解决?

Troubleshooting "Exception in thread 'main'" for Your N×N Array Code

First up, that generic error message is just the starting point—you need to look at the rest of the stack trace to find the actual exception type (like ArrayIndexOutOfBoundsException or NullPointerException) and the exact line number where it’s happening. That’s your key to figuring out what’s broken. Let’s walk through the most common issues and how to fix them:

1. Array Index Out of Bounds (The #1 Culprit)

Java uses 0-based indexing for arrays, so if your loops are running from 1 to N instead of 0 to N-1, you’ll definitely hit this error. For example:

// Wrong: Tries to access index N, which doesn't exist (arrays go up to N-1)
for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= N; j++) {
        System.out.print(arr[i][j] + " ");
    }
}

Quick Fix: Adjust your loops to start at 0 and stop before N:

// Correct: Uses valid indices 0 through N-1
for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
        // Your conditional check here (e.g., if (i == j) for diagonal elements)
        if (yourCondition) {
            System.out.print(arr[i][j] + " ");
        }
    }
    System.out.println(); // New line after each row
}

2. Uninitialized Array Rows (NullPointerException)

If you declared your 2D array but forgot to set up each individual row, trying to access arr[i][j] will throw a NullPointerException. Here’s what that mistake looks like:

// Wrong: Only creates the outer array shell, not the inner rows
int[][] arr = new int[N][];
// No code to initialize each arr[i] = new int[N];

Fix: Either initialize the entire array in one line, or loop to set up each row:

// Option 1: Initialize all rows at once (cleanest)
int[][] arr = new int[N][N];

// Option 2: If you need to initialize rows separately
int[][] arr = new int[N][];
for (int i = 0; i < N; i++) {
    arr[i] = new int[N]; // Create each row explicitly
}

3. Invalid N Value (NegativeArraySizeException)

If N is negative or zero, creating an array with new int[N][N] will throw a NegativeArraySizeException (for negative N) or create an empty array that causes issues when you try to access elements.
Fix: Add a quick check to make sure N is positive before you do anything else:

if (N <= 0) {
    System.err.println("Oops! N needs to be a positive integer.");
    return; // Exit the main method early to avoid further errors
}

4. Conditional Check Logic Gone Wrong

While this doesn’t always throw an exception, if your conditional uses index calculations that go out of bounds (like i + 1 without checking if it’s less than N), you’ll end up with an index error. Double-check any math inside your if statement that touches array indices.

Pro Debugging Tip: Print What’s Happening

If you’re still stuck, add simple print statements to see what’s going on with your array and indices. For example:

System.out.println("Current N value: " + N);
System.out.println("Total rows in array: " + arr.length);
for (int i = 0; i < arr.length; i++) {
    System.out.println("Row " + i + " has " + arr[i].length + " elements");
    for (int j = 0; j < arr[i].length; j++) {
        System.out.println("Trying to access arr[" + i + "][" + j + "]");
        // Your code here
    }
}

This will help you spot exactly where things go off the rails.

Content of the question originates from Stack Exchange, question author Simone Paolo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:18:45