0

I am trying to achieve even indentation in my output. So that even if the strings vary in length, the width between the strings will continue to match. What I mean is if I want to print a text file with a person's first name, age, and weight, but I want the indentation to remain even

Ryan       1          1
Alexander 25        180
Ashish P. 51        217
Ben       19        130

I know that a fixed width will not work because the name can be very long or short

writer.printf("%s%10d%10d", name, age, weight);

I am doing this using the PrintWriter.printf(), although I imagine it applies to System.out.printf() and .format() as well.

1 Answer 1

1

You may try to use tabulators to separate each field (\t char).

writer.printf("%s\t%d\t%d", name, age, weight);

But this may not work well, if the difference between length of shortest and longest name is bigger then the tabulator size. In this case you are out of luck and you will have to implement the logic yourself.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that was one of the first methods I tried, but because of the different in length especially for name and the fact that tabs are done in multiples 4, the width isn't divided neatly as I wanted.
You can iterate over names and find the longest name. Then calculate field position length and iterate again. Print number of spaces minus field length and field itself.

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.