以矩阵格式java打印出2d数组

时间:2015-03-21 11:43:24

标签: java

如何以精美的格式打印二维数组?

我想打印矩阵,如下所示,数字最多4个空格,小数字最多2个空格 例如xxxx.xx

 double A[][]= {
    { 3.152 ,96.1 , 77.12},
    { 608.12358 , -5.15412456453 , -36.1},
    { -753..555555,  6000.156564 , -155.541654}
};

//I need this output
   3.15 |   96.10 |   77.12
 608.12 |   -5.15 |  -36.10
-753.55 | 6000.15 | -155.54

2 个答案:

答案 0 :(得分:2)

这是一种方法:

// Convert to String[][]
int cols = A[0].length;
String[][] cells = new String[A.length][];
for (int row = 0; row < A.length; row++) {
    cells[row] = new String[cols];
    for (int col = 0; col < cols; col++)
        cells[row][col] = String.format("%.2f", A[row][col]);
}

// Compute widths
int[] widths = new int[cols];
for (int row = 0; row < A.length; row++) {
    for (int col = 0; col < cols; col++)
        widths[col] = Math.max(widths[col], cells[row][col].length());
}

// Print
for (int row = 0; row < A.length; row++) {
    for (int col = 0; col < cols; col++)
        System.out.printf("%" + widths[col] + "s%s",
                          cells[row][col],
                          col == cols - 1 ? "\n" : " | ");
}

<强>结果:

   3.15 |   96.10 |   77.12
 608.12 |   -5.15 |  -36.10
-753.56 | 6000.16 | -155.54

答案 1 :(得分:1)

这可能会有所帮助

public static void main(String[] args) {
    double A[][]= {
            { 3.152 ,96.1 , 77.12},
            { 608.12358 , -5.15412456453 , -36.1},
            { -753.555555,  6000.156564 , -155.541654}
        };
    //Number  of characters in format , here XXXX.XX length is 7
    int numberFormatLength=7;
    //Iterating through Array
    for(int i=0;i<A.length;i++){
        for(int j=0;j<A.length;j++){
            //Calculating number of spaces required.
            int spacesRequired=numberFormatLength-String.format("%.2f",A[i][j]).length();
            //Creating calculated number of spaces 
            String spaces = new String(new char[spacesRequired]).replace('\0', ' ');
            //formatting element to the format with  decimal place 2
            String arrayElement=String.format("%.2f",A[i][j]);
            //Using ternary operator to calculate what to print for every third Element in your array
            System.out.print((j/2==1)?(spaces+arrayElement+"\n"):(spaces+arrayElement+"|"));
        }

    }


}