java - 在 Java 中填充二维数组

标签 java arrays loops for-loop

所以这个问题更具理论性,因为我刚刚开始学习Java语言。这听起来可能很基本,但我还是想问。

这是我的二维数组的代码。

int matrix[][] = new int[5][];
for (int i = 0; i < matrix.length; i++){
        matrix[i] = new int[i];


            for(int j = 0; j < matrix[i].length; j++){
                matrix[i][j] = i;
            }
        }

第一个循环设置每个内部数组的元素数量。

当我为矩阵[ i ][ j ]分配“i”时,结果将是:

matrix[0] is <>
matrix[1] is <1>
matrix[2] is <2, 2>
matrix[3] is <3, 3, 3>
matrix[4] is <4, 4, 4, 4> 

同一代码中“j”的结果:

for(int j = 0; j < matrix[i].length; j++){
                matrix[i][j] = j;
            }

将是:

matrix[0] is <>
matrix[1] is <0>
matrix[2] is <0, 1>
matrix[3] is <0, 1, 2>
matrix[4] is <0, 1, 2, 3>

因此,我尝试理解为什么当我使用“i”填充数组时,数组中有重复的数字,而当我使用“j”的值时,它会产生从 0、1、2 开始的值。 ..

那么请您一步步向我解释一下for循环是如何迭代数组的,迭代数组的概念?我非常感谢所提供的帮助!谢谢!

最佳答案

有评论版本:

提示:当您不明白某段特定代码的工作原理时,自己写下这样的注释可以帮助您弄清楚。

//for every "available space" in our "matrix" variable
//we take one "step".
//this "step" is stored in a variable named "i"
for (int i = 0; i < matrix.length; i++)           //<-- outer loop starts here
{
        //initialise an array
        //this irray is as long as the number of loops we've made. (as long as "i" is high)
        //so the first one will be 0 length, the first will be 1 length, etc.
        matrix[i] = new int[i];


        //now, we start on the inner loop. keep in mind that we left "i" the same value.
        //for every available space in the array we just made, we take one "step"
        //this "step" is stored in a variable named "J"

        for(int j = 0; j < matrix[i].length; j++) // <-- inner loop starts here
        {
            //since we don't touch "i", it will be the same for as long as this loop runs.
            matrix[i][j] = i;

            //since we update "j" in every step of this loop, it will be 1 higher every time this loop runs.
            matrix[i][j] = j;
        } // <-- inner loop ends here

 } // <-- outer loop ends here

关于java - 在 Java 中填充二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24797855/

相关文章:

javascript - 如何获取关联数组循环中的索引 CoffeeScript

swift - while 循环回到不应该的地方。 ( swift )

java - 为 Android 加速 Jsoup

java - 如何从循环中删除 if else 条件?

arrays - 可被 k 整除的子数组数

Javascript 数组排序改变索引

javascript - 一次对数组的所有值使用 .addEventListener

python - 比较 numpy 数组中的以下两个值

java - 在recyclerview末尾添加进度条

java - 以看似随机的间隔获取 NullPointerException,不知道为什么