Pet*_*111 9 java arrays multidimensional-array
我有一个"连接四板",我用二维数组模拟(数组[x] [y] x = x坐标,y = y坐标).我必须使用"System.out.println",所以我必须遍历行.
我需要一种方法迭代这种方式[0,0] [1,0] [2,0] [3,0] [0,1] [1,1] [2,1]等
如果我使用正常程序:
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)
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为它以这种方式迭代[0,0] [0,1] [0,2] [0,3]等
正常的过程保持在x并增加y直到列的结尾,但我需要在y中说并递增x直到行的结尾.
Bha*_*rat 24
将它视为一个数组数组,这肯定会起作用.
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]);
}
}
Run Code Online (Sandbox Code Playgroud)
只需将索引的顺序颠倒过来:
for (int j = 0; j<array[0].length; j++){
for (int i = 0; i<array.length; i++){
Run Code Online (Sandbox Code Playgroud)
因为所有行都有相同数量的列,你可以首先使用这个条件j <array [0] .lengt for condition,因为你在迭代矩阵的事实
//This is The easiest I can Imagine .
// You need to just change the order of Columns and rows , Yours is printing columns X rows and the solution is printing them rows X columns
for(int rows=0;rows<array.length;rows++){
for(int columns=0;columns <array[rows].length;columns++){
System.out.print(array[rows][columns] + "\t" );}
System.out.println();}
Run Code Online (Sandbox Code Playgroud)
简单的想法:获取最长行的长度,迭代每一列,如果有元素则打印该行的内容。下面的代码可能有一些相差一的错误,因为它是在简单的文本编辑器中编码的。
int longestRow = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].length > longestRow) {
longestRow = array[i].length;
}
}
for (int j = 0; j < longestRow; j++) {
for (int i = 0; i < array.length; i++) {
if(array[i].length > j) {
System.out.println(array[i][j]);
}
}
}
Run Code Online (Sandbox Code Playgroud)