問題描述
我正在逐行打印數據,并希望它像表格一樣組織.
I'm printing data line by line and want it to be organized like a table.
我最初使用 firstName + ", " + lastName + " " + phoneNumber
.
但是對于一些較大的名字,電話號碼會被推到不對齊
But for some of the larger names, the phone number gets pushed out of alignment
我正在嘗試使用 String.format() 來實現此效果.誰能告訴我要使用的格式語法嗎?
I'm trying to use String.format() to achieve this effect. Can anyone tell me the format syntax to use?
我試過 String.format("%s, %s, %20s", firstName, lastName, phoneNumber)
,但這不是我想要的.我希望它看起來像這樣:
I tried String.format("%s, %s, %20s", firstName, lastName, phoneNumber)
, but that's not what I want. I want it to look like this:
約翰·史密斯 123456789
John, Smith 123456789
鮑勃,麥迪遜 123456789
Bob, Madison 123456789
查爾斯·理查茲 123456789
Charles, Richards 123456789
這些答案似乎適用于 System.out.println().但我需要它為 JTextArea 工作.我正在使用 textArea.setText()
These answers seem to work for System.out.println(). But I need it to work for a JTextArea. I'm using textArea.setText()
解決了.JTextArea 默認不使用等寬字體.我使用 setFont() 來改變它,現在它就像一個魅力.謝謝大家的解決方案.
Worked it out. JTextArea doesn't use monospaced fonts by default. I used setFont() to change that, and now it works like a charm. Thank you all for the solutions.
推薦答案
考慮使用負數作為長度說明符:%-20s
.例如:
consider using a negative number for your length specifier: %-20s
. For example:
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);
}
}
返回
Klein, Pete 555-123-4567
Jones, Jon 555-123-4567
Flinstone, Fred 555-123-4567
這篇關于如何在 Java 中使用 String.format() 來復制選項卡“ "?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!