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

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 i to iterate over the rows of your 10x10 array, starting at 0 and stopping when i hits 10 (since array indices go from 0 to 9 for a length-10 array).
  • But in the inner loop, you meant to increment j to iterate over each column in the current row. Instead, you're incrementing i here. This makes i skyrocket past the array's maximum index (9) in no time—by the time i hits 10, trying to access gametable[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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:34:54