我声明了一个带有一些值的 2D int 数组,我需要在控制台上反转行/列。 第一行必须垂直显示为第一列,第二行必须垂直显示为第二列,依此类推。 例如, [0][0] 、 [0][1] 、 [0][2] 的值应垂直打印,并且第二行即将出现的值也应垂直向右对齐.
这是到目前为止我的代码!
public class Print {
public static void main(String[] args) {
int firstarray[][] = {{8,9,10,11},{12,13,14,15}};
System.out.println("This is the inverted array");
display(firstarray);
}
public static void display (int x[][]){
for(int row=0; row<x.length; row++){
for(int column = 0; column<x[row].length; column++){
System.out.println(x[row][column] + "\t");
}
System.out.print("\n");
}
}
}
当前输出(未正确对齐):
This is the inverted array
8
9
10
11
12
13
14
15
正确的输出应该是:
This is the inverted array
8,12
9,13
10,14
11,15
最佳答案
只需更改你的 for 循环即可,
for(int row=0; row<1; row++){
for(int column = 0; column<x[row].length; column++){
System.out.println(x[row][column] + "\t"+x[row+1][column] );
}
System.out.print("\n");
}
即使您有 5000 行,下面的内容也将起作用,
for(int row=0; row<x.length-1; row++){
for (int column = 0; column < x.length; column++) {
System.out.print(x[column][row] + "\t" );
}
System.out.println();
}
关于java - 对齐二维数组打印输出 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20632183/