Java二维数组循环触发ArrayIndexOutOfBoundsException的解决方法
Fixing the ArrayIndexOutOfBoundsException in Your Java 2D Array Code
Hey, let's break down why you're getting that ArrayIndexOutOfBoundsException and fix it right away!
First off, the issue is a tiny but critical typo in your nested for loop—you accidentally used i++ instead of j++ in the inner loop!
Why this breaks things:
- Your outer loop uses
ito iterate over the rows of your 10x10 array, starting at 0 and stopping whenihits 10 (since array indices go from 0 to 9 for a length-10 array). - But in the inner loop, you meant to increment
jto iterate over each column in the current row. Instead, you're incrementingihere. This makesiskyrocket past the array's maximum index (9) in no time—by the timeihits 10, trying to accessgametable[i][j]is asking for an index that doesn't exist, hence the exception.
Here's the corrected code:
int x=10,y=10; char[][] gametable=new char[x][y]; for(int i=0;i<gametable.length;i++) { for(int j=0;j<gametable[i].length;j++) { // Changed i++ to j++ here gametable[i][j]='.'; System.out.print(gametable[i][j]); } System.out.println(); // Swapped out println(i) for a plain newline to format the grid properly }
A quick extra tip:
I also swapped System.out.println(i) with a plain System.out.println()—your original code would print the row index after each line of dots, which I assume wasn't your goal. This change will output a clean 10x10 grid of dots, each row on its own line.
Nested loops are tricky for exactly these little mix-ups—always double-check that your loop variable matches the increment!
内容的提问来源于stack exchange,提问作者Hui HiuShi
相关产品推荐
相关产品推荐

