I was wondering if someone can show me how to use the format method for Java Strings. For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
To answer your updated question you can do
prints
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the
StringBuilder
class too which is more efficient.If you want a minimum of 4 characters, for instance,
The output looks like this:
As a reference I recommend Javadoc on formatter syntax
For decimal values you can use DecimalFormat
and output will be:
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html