我想为 Matrix 类编写一个 toString
方法,我需要在其中返回包含矩阵的格式化字符串。矩阵中的条目在长度上有很大不同,所以仅仅用 TAB
分隔条目是行不通的。现在我有以下内容:
public String toString(){
String str = "";
for(int i=0;i < _dim[0];i++){
for(int j=0;j < _dim[1];j++){
str += this.values[i][j] + "\t" + "\t";
}
str += "\n";
}
return str;
}
这给了我这样的东西。
3.2004951E7 -1.591328E7 17839.0
-35882.0 17841.0 -20.0
1794.0 -892.0 1.0
有没有办法在事先不知道每个条目要多长时间的情况下正确对齐地打印这些内容?
谢谢。
最佳答案
Is there a way to print these properly aligned without knowing in advance how long each entry is going to be?
我不认为有任何可用的内置库函数可以做这样的事情
为我们。我们将不得不制作自己的格式,例如使用:%-xs
:
- 创建一维数组:
maxWidth[col]
求出每列的最大宽度:列的大小等于二维数组的列数。 - 访问二维数组,找出每列的最大宽度
- 使用
"%-"+maxWidth[col]+"s "
为每列创建格式字符串,其中-
在%
之后> 指定格式为左对齐。 - 请查看 formatting Numeric Print Output了解更多详情。
示例代码:
String data[][] = {{3.2004951E7+"" , -1.591328E7+"", 17839.0+"" },
{-35882.0 +"" , -17841.0+"", -20.0+"" }};
int col = data[0].length;
int row = data.length;
int maxWidth[] = new int[col];
for(String[] rowD : data)
for(int i=0; i< col; i++)
{
if(maxWidth[i] < rowD[i].length())
maxWidth[i] = rowD[i].length();
}
String format = "";
for(int x : maxWidth)
format += "%-"+(x+2)+"s ";
format +="%n";
System.err.println(format);
for(String[] rowD : data)
{
System.out.printf(format, rowD);
}
输出:
3.2004951E7 -1.591328E7 17839.0
-35882.0 -17841.0 -20.0
关于Java:将条目长度变化很大的二维数组作为格式化字符串返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20457971/