java - 以矩阵格式打印二维数组java

标签 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

最佳答案

这是一种方法:

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

关于java - 以矩阵格式打印二维数组java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29182315/

相关文章:

java - 我是否需要在其自己的文件中将枚举定义为 'public',以便它可以在自己的包外被识别?

java工厂和观察者模式

java - 从 Eclipse 运行 Serenity 测试时如何指定 Selenium Hub URL?

java - 2 个互斥的InputComponents 引用相同的Field 则更新相同的字段两次

java - 返回一个新字符串,所有出现的输入字符都移到末尾

java - 在循环内的 Highcharts 中创建多个系列

java - POI中的空指针问题

java - Kafka 消费者 - 暂停对特定 Kafka 主题分区的事件轮询,以将其用作延迟队列

java - ExecutorService线程安全

java - 面向 Java 开发人员的 Groovy 迁移