首页 > 解决方案 > 锯齿状数组的顺序填充。这段代码是如何工作的?

问题描述

我正在通过锯齿状阵列上的解决方案之一,无法遵循以下几行。任何人都可以帮助我理解count这里是如何使用的。我确实了解 Java 的基础知识,但不明白为什么在这里使用 count。

在 Java 中演示二维锯齿状数组的程序:

int arr[][] = new int[2][];
// Making the above array Jagged
// First row has 3 columns
arr[0] = new int[3];
// Second row has 2 columns
arr[1] = new int[2];
// Initializing array
int count = 0;//why do we need count 
for (int i = 0; i < arr.length; i++)
    for (int j = 0; j < arr[i].length; j++)
        arr[i][j] = count++; //how this line of code will work

标签: javaarraysmultidimensional-arrayjagged-arrays

解决方案


您可以将输出添加到此代码。需要该count变量来顺序地用整数填充数组,0依此类推。

int[][] arr = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
// iterate through the rows of the array
for (int i = 0; i < arr.length; i++)
    // iterate through the columns of the array
    for (int j = 0; j < arr[i].length; j++)
        // set the array element and increment the counter
        arr[i][j] = count++;

// output
for (int[] row : arr) System.out.println(Arrays.toString(row));

输出:

[0, 1, 2]
[3, 4]

推荐阅读