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

如何修复3x3矩阵遍历中的Java IndexOutOfBoundsException?

解决IndexOutOfBoundsException的行列索引计算问题

你的3x3矩阵测试场景下,代码抛出索引3越界异常,核心原因是行列索引的转换逻辑完全错误,导致列索引超出了0-2的合法范围。

看你原来的列索引计算:i - (i % curBoard[0].length),以i=3为例,curBoard[0].length=3,i%3=0,计算结果是3-0=3,直接超出了列索引的最大值2,自然触发IndexOutOfBoundsException。而你尝试减1后,当i=0时,0 - (0%3) -1 = -1,又会触发负索引的越界错误。

正确的行列索引转换逻辑

对于一维索引i(范围0到rows*cols-1),转换为二维矩阵的行列索引应该是:

  • 行索引:i / cols(cols是矩阵的列数,即curBoard[0].length)
  • 列索引:i % cols

以3x3矩阵为例:

  • i=0 → 0/3=0行,0%3=0列
  • i=3 →3/3=1行,3%3=0列
  • i=8 →8/3=2行,8%3=2列
    完全符合3x3矩阵的合法索引范围(行0-2,列0-2)

修改后的代码

int outOfOrderCount = 0;
int val = 0;
int curVal = 0;
int rows = curBoard.length;
int cols = curBoard[0].length;
for(int i = 0; i < rows * cols; i++) {
    // 正确的行列索引转换
    int row = i / cols;
    int col = i % cols;
    val = curBoard[row][col];
    
    for(int cidx = i + 1; cidx < rows * cols; cidx++) {
        int cRow = cidx / cols;
        int cCol = cidx % cols;
        curVal = curBoard[cRow][cCol];
        
        if(val < curVal) {
            outOfOrderCount++;
        }
    }
}

错误原因说明

你之前混淆了行和列的计算逻辑:

  1. 错误用i % curBoard.length计算行索引,导致i超过行数时,行索引循环回到0(比如i=3时,3%3=0,回到第0行),不符合一维索引到二维矩阵的映射规则;
  2. 列索引的计算方式完全错误,直接生成了等于矩阵列数的索引值,触发越界。

内容的提问来源于stack exchange,提问作者Linux noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 16:50:22