用Java填充二维数组

时间:2014-07-17 07:55:00

标签: 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;
            }
        }

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

当我指定&#34; i&#34;对于矩阵[i] [j],结果将是:

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> 

&#34; j&#34;的结果在相同的代码中:

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>

所以我试着理解为什么当我使用&#34; i&#34;为了填充数组,我在数组中重复数字,而我使用&#34; j&#34;它产生的值从0,1,2 ......

开始

那么请你一步一步地向我解释循环如何迭代数组,迭代数组的概念?我真的很感激给予的帮助!谢谢!

3 个答案:

答案 0 :(得分:1)

你有嵌套循环;对于第二个循环的每次迭代,第一个值将重复(对于第一个示例)。因此,举一个简单的例子,我们拥有的是......

在外循环的第一次迭代中 - i = 1,  内环j = 1。

所以我们有1 [1,2,3,..., n ]。

第二个例子j&#34;走路&#34;一对一(即; 1,2,3,4 ......)。 <{1}}代表

&#34; [1,2,3,..., n ]&#34;以上例子。

是嵌套循环的本质。

答案 1 :(得分:1)

有评论版:

提示:当您不了解某段代码的工作原理时,请自行编写类似的评论。

//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

答案 2 :(得分:0)

让我们选择一个名为i的简单数组:

i = [a, b, c]

现在让我们为a,b,c:

创建另一个数组
a=[ 0, 1, 2 ] 
b=[ 0, 1, 2 ]
c=[ 0, 1, 2 ]

基本上,我们有:

row a = 0 1 2
row b = 0 1 2
row c = 0 1 2

(i)的第一个循环(a,b,c)。第二个for,循环在列(0,1,2)

所以,如果你说&#34; row [a] [2]&#34;你必须选择一行,然后选择2(java中的第三列)。

相关问题