遍历二维数组 [英] Iterate through 2 dimensional array
问题描述
我有一个连接四块板",我用一个二维数组(array[x][y] x=x 坐标,y = y 坐标)模拟它.我必须使用System.out.println",所以我必须遍历行.
I have a "connect four board" which I simulate with a 2d array (array[x][y] x=x coordinate, y = y coordinate). I have to use "System.out.println", so I have to iterate through the rows.
我需要一种方法来迭代这种方式 [0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1] 等
I need a way to iterate this way [0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1] etc
如果我使用正常程序:
for (int i = 0; i<array.length; i++){
for (int j = 0; j<array[i].length; j++){
string += array[i][j];
} System.out.println(string)
}
它不起作用,因为它以这种方式迭代 [0,0] [0,1] [0,2] [0,3] 等
it doesnt work because it iterates this way [0,0] [0,1] [0,2] [0,3] etc
正常程序停留在 x 中并递增 y 直到列的末尾,但我需要在 y 中说并递增 x 直到行尾.
The normal procedure stays in x and increments y until the end of the column, but i need to say in y and increment x until the end of the row.
推荐答案
将其视为一个数组数组,这肯定会起作用.
Consider it as an array of arrays and this will work for sure.
int mat[][] = { {10, 20, 30, 40, 50, 60, 70, 80, 90},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50, 51, 89},
};
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[i].length; j++) {
System.out.println("Values at arr["+i+"]["+j+"] is "+mat[i][j]);
}
}
这篇关于遍历二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!