用于Strings的Java输出格式

我想知道如果有人能告诉我如何使用Javastring的格式化方法。 例如,如果我想所有我的输出的宽度是相同的

例如,假设我总是希望我的输出是相同的

Name = Bob Age = 27 Occupation = Student Status = Single 

在这个例子中,所有的输出整齐地格式化在一起, 我将如何完成这与格式方法。

编辑:这是一个非常原始的答案,但我不能删除它,因为它被接受。 请参阅下面的答案,以获得更好的解决scheme

为什么不dynamic地生成一个空白string来插入语句。

所以如果你想让他们都从第50个angular色开始

 String key = "Name ="; String space = ""; for(int i; i<(50-key.length); i++) {space = space + " ";} String value = "Bob\n"; System.out.println(key+space+value); 

把所有这些放在一个循环中,并在每次迭代之前初始化/设置“键”和“值”variables,你是黄金。 我也会使用更高效的StringBuilder类。

 System.out.println(String.format("%-20s= %s" , "label", "content" )); 
  • 其中%s是您的string的占位符。
  • “ – ”使结果左alignment。
  • 20是第一个string的宽度

输出如下所示:

 label = content 

作为参考,我build议在格式化器语法上使用Javadoc

例如,如果您至less需要4个字符,

 System.out.println(String.format("%4d", 5)); // Results in " 5", minimum of 4 characters 

但是,真的,你需要学习如何理解文档。

要回答您更新的问题,你可以做

 String[] lines = ("Name = Bob\n" + "Age = 27\n" + "Occupation = Student\n" + "Status = Single").split("\n"); for (String line : lines) { String[] parts = line.split(" = +"); System.out.printf("%-19s %s%n", parts[0] + " =", parts[1]); } 

版画

 Name = Bob Age = 27 Occupation = Student Status = Single 
 @Override public String toString() { return String.format("%15s /n %15d /n %15s /n %15s",name,age,Occupation,status); } 

对于十进制值,可以使用DecimalFormat

 import java.text.*; public class DecimalFormatDemo { static public void customFormat(String pattern, double value ) { DecimalFormat myFormatter = new DecimalFormat(pattern); String output = myFormatter.format(value); System.out.println(value + " " + pattern + " " + output); } static public void main(String[] args) { customFormat("###,###.###", 123456.789); customFormat("###.##", 123456.789); customFormat("000000.000", 123.78); customFormat("$###,###.###", 12345.67); } } 

和输出将是:

 123456.789 ###,###.### 123,456.789 123456.789 ###.## 123456.79 123.78 000000.000 000123.780 12345.67 $###,###.### $12,345.67 

更多细节请看这里:

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html