gpt4 book ai didi

Java Formatter 类,有没有一种简单的方法可以用空格自动填充列?

转载 作者:行者123 更新时间:2023-12-03 21:26:00 24 4
gpt4 key购买 nike

假设您有一些表格数据,其中数据长度可能会有所不同,Formatter 类是否有自动调整填充的规定?

所以不是这个(注意 A 列):

columnA    columnB     
1 34.34
10 34.34
100 34.34
1000 34.34

你明白了(注意 B 列):

columnA    columnB     
1 34.34
10 34.34
100 34.34
1000 34.34

到目前为止,我已经尝试过这个,它只简单地包含 %5s %5s 之间的空格,但它们是静态的,不会调整以产生我想要的结果。我的印象是 %5s 中的 5 会自动填充 5 个空格

Formatter formatter = new Formatter();
formatter.format("%5s %5s", columnAdata, columnBdata);

最佳答案

绝对有可能。我知道的方式是为第一列中的数据配置最小宽度。为此,您需要结合使用 width 属性和 left-justification (均记录在 the Javadoc 中)。这是您的开始:

System.out.printf("%-10d %d%n", 1, 100);
System.out.printf("%-10d %d%n", 10, 100);
System.out.printf("%-10d %d%n", 100, 100);

这打印:

1          100
10 100
100 100

格式%-10d %d%n可以解释如下:

%-10d: first field

%: start field
-: left-justify
10: output a minimum of 10 characters
d: format as a decimal integer

%d: second field, using defaults for decimal integer
%n: newline

关于Java Formatter 类,有没有一种简单的方法可以用空格自动填充列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7602562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com