1

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));
1
  • 4
    You mean like String.format()? Commented Jan 9, 2016 at 20:46

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.