初始化使用嵌套的for循环二维数组的价值观 [英] Initialize Values of 2D Array using Nested For Loops
本文介绍了初始化使用嵌套的for循环二维数组的价值观的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图格式化数组如下:
I am trying to format an array that is the following:
[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
[11] [12] [13] [14] [15]
我怎么能初始化二维数组和嵌套的值使用for循环?
How could I initialize the two dimensional array and the values using nested for loops?
推荐答案
我觉得你有二维数组的误解。想想他们beeing包含数组的数组。
I think you have a misunderstanding of two dimensional arrays. Think of them beeing arrays containing arrays.
如果你真的想这样的:
[[1] [2] [3] [4] [5]
[6] [7] [8] [9] [10]
[11] [12] [13] [14] [15]]
您可以将其初始化像这样:
You could initialize it like that:
int[][] array2d = new int[15][1]
for (int i = 0; i < array2d.length; i++) {
array2d[i][0] = i + 1;
}
如果在FATC,你真正想要的是:
If in fatc, what you really want is:
[[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[11, 12, 13, 14, 15]]
您可以使用:
int[][] array2d = new int[3][5]
for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
array2d[i][j] = (i * array2d[0].length) + j + 1;
}
}
这篇关于初始化使用嵌套的for循环二维数组的价值观的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文