Java Formatter class, is there an easy way to auto pad columns with spaces?
Say you have some tabular data where the datas length can vary, is there a provision with the Formatter class to auto adjust the padding?
So instead of this (note column A):
columnA columnB
1 34.34 开发者_StackOverflow
10 34.34
100 34.34
1000 34.34
You get this (note column B):
columnA columnB
1 34.34
10 34.34
100 34.34
1000 34.34
Thus far, i've tried this which only simply includes the spaces between %5s %5s, but they are static and do not adjust to produce the results I want. I was under the impression that the 5 in %5s would auto pad 5 spaces
Formatter formatter = new Formatter();
formatter.format("%5s %5s", columnAdata, columnBdata);
It's definitely possible. The way I know off-hand is to configure a minimum width for data in your first column. To do this you want to make use of the width attribute in conjunction with left-justification (both documented in the Javadoc). Here's a start for you:
System.out.printf("%-10d %d%n", 1, 100);
System.out.printf("%-10d %d%n", 10, 100);
System.out.printf("%-10d %d%n", 100, 100);
This prints:
1 100
10 100
100 100
The format %-10d %d%n
can be explained as follows:
%-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
精彩评论