要将字符串格式化为表格,请使用System.out.format。
对于我们的表,我们给了15s,这意味着15个空格。对于索引之后的第二列以相同的方式进行。
|%1$-15s|%2$-15s|
将上述内容添加到字符串中,这样就不必一次又一次地添加它。
以下是一个示例。
public class Demo {
public static void main(String []args) {
String strFormat = "|%1$-15s|%2$-15s|\n";
System.out.format(strFormat, "One", "Two");
System.out.format(strFormat, "Three", "Four");
System.out.format(strFormat, "Five", "Six");
System.out.format(strFormat, "Seven", "Eight");
System.out.format(strFormat, "Nine", "Ten");
System.out.format(strFormat, "Eleven", "Twelve");
System.out.format(strFormat, "Thirteen", "Fourteen");
System.out.format(strFormat, "Fifteen", "Sixteen");
}
}输出结果
|One |Two | |Three |Four | |Five |Six | |Seven |Eight | |Nine |Ten | |Eleven |Twelve | |Thirteen |Fourteen | |Fifteen |Sixteen |