[英]Creating two-dimensional arrays using nested-loop
I am trying to understand this code from the book.我试图从书中理解这段代码。
int[][] grade = {
{ 1, 0, 1 },
{ 0, 1, 0 },
{ 1, 0, 1 }
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j)
System.out.print(grade[i][j] + grade[j][i] + " ");
else
System.out.print(grade[i][j] * grade[j][i] + " ");
}
System.out.println(" ");
}
I understand the logic of a two-dimensional arrays being rows and columns.我理解二维数组是行和列的逻辑。 I just don't understand how the answer came to be this.我只是不明白答案是怎么来的。
2 0 1
0 2 0
1 0 2
It loops through the 2 dimensional array.它遍历二维数组。 If i is equal to j, eg ( 0,0 1,1 2,2 ) then it adds grade[i][j] with grade[j][i].如果 i 等于 j,例如 ( 0,0 1,1 2,2 ) 则它将 Grade[i][j] 与 Grade[j][i] 相加。 Since i and j are equal it adds the location with itself.由于 i 和 j 相等,因此将位置与自身相加。
When i is not equal to j it multiplies grade[i][j] with grade[j][i].当 i 不等于 j 时,它将等级 [i][j] 与等级 [j][i] 相乘。
Since they are not equal it multiplies 2 different positions in the grid.由于它们不相等,因此将网格中的 2 个不同位置相乘。 eg例如
grade [3][1] is multiplied by grade[1][3], not by itself.等级 [3][1] 乘以等级 [1][3],而不是乘以自身。
If you changed grade[1][3] to 2, then all corners would be output as 2如果将 grade[1][3] 更改为 2,则所有角都将输出为 2
The input:输入:
1 0 2
0 1 0
1 0 1
would output:会输出:
2 0 2
0 2 0
2 0 2
It basically loops through the two dimensional array and if it sees that the column and row number (i and j) are the same it will add it with itself.它基本上遍历二维数组,如果它看到列号和行号(i 和 j)相同,它将与自身相加。 ie times the diagonal by two.即对角线乘以二。 And for the rest of the entries it will multiply with itself.对于其余的条目,它将与自身相乘。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.