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

二维数组求偶数和与奇数积时遇ArrayIndexOutOfBoundsException问题

Hey there! Let's break down why you're hitting that java.lang.ArrayIndexOutOfBoundsException on the line if(m[i][j]%2==0):

Common Causes of the Array Index Out-of-Bounds Error in Your Code

This exception pops up when you try to access an array position that doesn't exist. For your specific line of code, here are the most likely culprits:

  • Using a fixed column length for all rows (with irregular 2D arrays)
    Java allows 2D arrays where each row can have a different length (called jagged arrays). If you set your column loop to use a fixed value like m[0].length (assuming all rows are the same length as the first), but some rows are shorter, you'll hit the error when you try to access an index that doesn't exist in those shorter rows.
    Example of the mistake:

    int[][] m = {{1,2}, {3}}; // Second row only has 1 element
    for(int i=0; i<m.length; i++){
        // Wrong: uses first row's length for all rows
        for(int j=0; j<m[0].length; j++){
            if(m[i][j]%2==0){...} // When i=1, j=1 is out of bounds
        }
    }
    

    Fix: Use m[i].length as the upper limit for the column loop, so each row uses its own actual length.

  • Starting loop indices at 1 instead of 0
    Java array indices start at 0, not 1. If your loops look like for(int i=1; i<=m.length; i++) (or similar for columns), you'll end up trying to access m[m.length][...] which is beyond the array's actual bounds.

  • Mixing up row and column indices
    If your array has different row and column counts (e.g., 3 rows and 2 columns), accidentally writing m[j][i] instead of m[i][j] (or vice versa) can lead to accessing indices that don't exist once the loop variables exceed the smaller dimension.

  • Mismatched array declaration and initialization
    If you declared your array with a certain row/column length (like int[][] m = new int[3][2];) but then assigned fewer elements to some rows, you'll end up trying to access positions that weren't initialized.

Here's a quick fixed example that handles jagged arrays correctly:

int evenSum = 0;
int oddProduct = 1;
int[][] m = {{1,2,3}, {4,5}, {6}};

for(int i=0; i<m.length; i++){
    // Use current row's length for column loop
    for(int j=0; j<m[i].length; j++){
        if(m[i][j]%2 == 0){
            evenSum += m[i][j];
        } else {
            oddProduct *= m[i][j];
        }
    }
}

内容的提问来源于stack exchange,提问作者John Doe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:18:04