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

Jagged Array触发ArrayIndexOutOfBoundsException的原因分析

锯齿数组垂直打印时ArrayIndexOutOfBoundsException异常原因分析

你编写了将锯齿数组按垂直列打印的代码,nums1的每个子数组长度均为3,运行正常;但nums2为子数组长度不一致的锯齿数组,运行时触发ArrayIndexOutOfBoundsException。相关代码及错误信息如下:

代码实现

public class test {
public static void main(String[] args) {
    double nums1[][] =
    {
        {
            1, 2, 3
        }, 
        {
            4, 5, 6
        }, 
        {
            7, 8, 9
        }
    };
    double nums2[][] ={ {3.23, 4.28, 2.63, 2.89},{1.63, 8.46, 4.11},{0.23, 7.14, 1.26, 9.16, 8.01},{4.20}
    };

    System.out.println("\n\nPrint nums1 vertically");
    printVertical(nums1);

    System.out.println("\n\nPrint nums2 vertically");
   printVertical(nums2);
}

public static void printVertical(double[][] nums)
{
    for (int i = nums.length - 1; i >= 0; i--) {
        for (int j = 0; j < nums[i].length; j++) {
                System.out.print(nums[j][i] + "      ");
        }
        System.out.println();

    }
    for (int i = 0; i < nums.length; i++) {
        System.out.print("Col " + (i + 1) + "    ");
    }
}

错误信息

3.0      6.0      9.0
2.0      5.0      8.0
1.0      4.0      7.0 Col 1    Col 2    Col 3

Print nums2 vertically
2.89
2.63      4.11      1.26      Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 1
        at test.printVertical(test.java:29)
        at test.main(test.java:22)

异常产生的原因

你的printVertical方法逻辑仅适配子数组长度完全一致的二维数组,处理锯齿数组时存在两个致命逻辑错误:

  • 循环边界与索引访问逻辑不匹配
    外层循环用nums.length(二维数组的行数)作为列的遍历上限,但锯齿数组中不同行的子数组长度(列数)差异很大。当外层循环到i=2时,内层循环的上限是nums[2].length(值为5),此时j会遍历到3,而nums[3]是长度仅为1的子数组,根本没有索引为2的元素,访问nums[3][2]直接触发数组越界。

  • 行和列的逻辑混淆
    垂直列打印的核心是遍历所有可能的列位置,而锯齿数组的最大列数应该是所有子数组中最长的那个长度,不是二维数组的行数。原代码错误地将行数当作列数上限,同时颠倒了行和列的索引访问顺序,导致在子数组长度不足时访问不存在的索引位置。

举个具体出错场景:
当外层循环i=2(对应要打印第3列的元素),内层循环j从0到4,当j=3时,nums[3]是{4.20},它的长度只有1,nums[3][2]是不存在的索引,因此抛出ArrayIndexOutOfBoundsException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:35:32