In Java is there any way to use printf to add spaces to the end of a string to ensure all strings are the same length in the command line.
I have a program which returns records but I need to display them as so...
Bob 27 007895
Christopher 32 007856
Essentially I want each name to take up 30 characters so the columns all align. At the moment I.m using a tab at the end of the string to create the columns but there are some names which cause all the columns to miss align (Christopher is one of them).... So im assuming there is a much better way to do this?
System.out.print(Bob.getName() + "\t");
System.out.print(Bob.getAge() + "\t");
Sstem.out.print(Bob.getRegnumber() + "\t");
System.out.print(Chris.getName() + "\t");
System.out.print(Chris.getAge() + "\t");
Sstem.out.print(Chris.getRegnumber() + "\t");
I'm outputting to the comandline not using a GUI.
Cheers
Here is a cheat sheet that summarizes the various printf symbols and how to use them.
You want to specify a particular max size for each of the fields to make sure that all of the fields line up. If you do not specify a max size then you will get the mis-alignment again.
So something like the following format is needed: "%-30.30s %8d %8d\n"
If the last field is a string and not an integer you will need something like "%-30.30s %8d %10.10s\n".
The "%-30.30s" will print left justified max of 30 chars. "%10.10s" will print right justified max of 10 characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With