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.
The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.
%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"
They are format specifiers used in some methods like printf() to format the string. The %s is replaced with the times value (below in the example). The %n tells the console print it in a new line.
the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.
System.out.println(String.format("%-20s= %s" , "label", "content" ));
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
If you want a minimum of 4 characters, for instance,
System.out.println(String.format("%4d", 5)); // Results in " 5", minimum of 4 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