有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

如何以精细格式打印二维数组

我想打印如下所示的矩阵,数字最多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

共 (1) 个答案

  1. # 1 楼答案

    这里有一种方法:

    // 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