数组中的数组,100 行,动态列

Arrays in array, 100 rows, dynamic columns

我想得到这个:

arrays[1][0] = 5

arrays[2][0] = 7
arrays[2][1] = 2

arrays[3][0] = 6
arrays[3][1] = 9
arrays[3][2] = 11

所以我希望 arrays[1][] 有一个随机数据元素,arrays[2][] 有 2 个随机数据元素等等,直到我有 100 个数组。所以我的最后一个数组将是 arrays[100][],其中包含 100 个随机数据元素。

这是我现在的代码,但在执行 arrays[i][j] = generator.nextInt(max) 时出现 NullPointerException:

Comparable[][] arrays = new Comparable[100][];
    for (int i=1; i<101;i++){
        for (int j=0; j <= i-1; j++){
            arrays[i][j] = generator.nextInt(max);
        }
    }

你的

Comparable[][] arrays = new Comparable[100][];

line 仅创建 outermost 数组。您需要创建其中的数组,例如像这样:

Comparable[][] arrays = new Comparable[100][];
for (int i=1; i<101;i++){
    arrays[i] = new Comparable[/* relevant length here*/]; // <====
    for (int j=0; j <= i-1; j++){
        arrays[i][j] = generator.nextInt(max);
    }
}

我不清楚你为什么在 1 开始 i 或者随机性应该在哪里(我猜是 /* relevant length here */),但希望这能为你指明正确的方向.