Reputation: 23
I want to print something like a chart with minimum space in each block and a certain alignment to the space it takes up. Let's say I had a chart in python like:
Format = """ X | Y | Z
{:^5}|{:>5}|{:>5}"""
print(Format.format(4, 64, 23))
How would I do this in java. Everything I've tried doesn't include minimum white space or alignment.
System.out.println(" X | Y | Z ");
System.out.println(MessageFormat.format("{0}|{1}|{2}", 4, 64, 23));
Upvotes: 1
Views: 602
Reputation: 201437
You could use String.format(String, Object...)
or use System.out.printf
(which can use the same String, Object...
) to output it directly, like
System.out.printf("%-5s %5s %5s%n", "X", "Y", "Z");
System.out.printf("%-5d % 5d % 5d%n", 4, 64, 23);
and I get
X Y Z
4 64 23
Upvotes: 4