如何以精细格式打印二维数组?
我想打印如下所示的矩阵,数字最多 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/