java - 对齐二维数组打印输出 [Java]

标签 java arrays printing console

我声明了一个带有一些值的 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/

相关文章:

java - 授权 App Engine Java Servlet 在 eclipse 中使用 Cloud SQL

java - java中的空指针异常。

javascript - ExtendScript 从搜索的 Comp 结果中获取索引号

android - 在没有设置弹出窗口的情况下使用 Android 进行打印

css - 从 window.print() 中删除页眉和页脚

java - JTS/Geotools 修正多个几何体的并集/差集

java - 比较两个字节数组? ( java )

java - 是否使用多维数组,或者带有 hashCodes 的简单数组

C - 数组求和函数不断返回零

c# - 将文件发送到打印机,没有打印任何内容