二维数组求偶数和与奇数积时遇ArrayIndexOutOfBoundsException问题
Hey there! Let's break down why you're hitting that java.lang.ArrayIndexOutOfBoundsException on the line if(m[i][j]%2==0):
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 likem[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].lengthas 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 likefor(int i=1; i<=m.length; i++)(or similar for columns), you'll end up trying to accessm[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 writingm[j][i]instead ofm[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 (likeint[][] 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

