我正在逐行打印数据,并希望它像表格一样组织.
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模板网!
如何在 JTextPane 中的组件周围环绕文本?How to wrap text around components in a JTextPane?(如何在 JTextPane 中的组件周围环绕文本?)
MyBatis,如何获取插入的自动生成密钥?[MySql]MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何获取插入的自动生成密钥?[MySql])
在 Java 中插入 Oracle 嵌套表Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java:如何将 CLOB 插入 oracle 数据库Java: How to insert CLOB into oracle database(Java:如何将 CLOB 插入 oracle 数据库)
为什么 Spring-data-jdbc 不保存我的 Car 对象?Why does Spring-data-jdbc not save my Car object?(为什么 Spring-data-jdbc 不保存我的 Car 对象?)
使用线程逐块处理文件Use threading to process file chunk by chunk(使用线程逐块处理文件)