ask*_*ask 16 java format syntax tabs
我正在逐行打印数据,并希望它像桌子一样组织.
我最初用过firstName + ", " + lastName + "\t" + phoneNumber
.
但对于一些较大的名字,电话号码被推离了对齐
我正在尝试使用String.format()来实现此效果.谁能告诉我要使用的格式语法?
我试过了String.format("%s, %s, %20s", firstName, lastName, phoneNumber)
,但这不是我想要的.我希望它看起来像这样:
约翰,史密斯123456789
Bob,Madison 123456789
查尔斯,理查兹123456789
编辑:这些答案似乎适用于System.out.println().但我需要它为JTextArea工作.我正在使用textArea.setText()
解决了这个问题.默认情况下,JTextArea不使用等宽字体.我使用setFont()来改变它,现在它就像一个魅力.谢谢大家的解决方案.
Hov*_*els 20
考虑使用负数来表示长度说明符:%-20s
.例如:
public static void main(String[] args) {
String[] firstNames = {"Pete", "Jon", "Fred"};
String[] lastNames = {"Klein", "Jones", "Flinstone"};
String phoneNumber = "555-123-4567";
for (int i = 0; i < firstNames.length; i++) {
String foo = String.format("%-20s %s", lastNames[i] + ", " +
firstNames[i], phoneNumber);
System.out.println(foo);
}
}
Run Code Online (Sandbox Code Playgroud)
回报
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567
Run Code Online (Sandbox Code Playgroud)
Yog*_*ngh 10
尝试将宽度放入第二个占位符,-
右边填充符号为:
String.format("%s, %-20s %s", firstName, lastName, phoneNumber)
Run Code Online (Sandbox Code Playgroud)
这将指定宽度为第二个参数(姓氏),右边填充,电话号码将仅在指定的宽度字符串后面开始.
编辑:演示:
String firstName = "John";
String lastName = "Smith";
String phoneNumber = "1234456677";
System.out.println(String.format("%s, %-20s %s",firstName, lastName, phoneNumber));
Run Code Online (Sandbox Code Playgroud)
打印:
约翰,史密斯1234456677