Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java output formatting for Strings

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.

like image 738
Steffan Harris Avatar asked Dec 11 '10 18:12

Steffan Harris


People also ask

How do I return a string format in Java?

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.

What is %d and %s in Java?

%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"

What is %s and %N in Java?

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.

What does %s in Java mean?

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.


2 Answers

System.out.println(String.format("%-20s= %s" , "label", "content" )); 
  • Where %s is a placeholder for you string.
  • The '-' makes the result left-justified.
  • 20 is the width of the first string

The output looks like this:

label               = content 

As a reference I recommend Javadoc on formatter syntax

like image 149
stacker Avatar answered Sep 18 '22 17:09

stacker


If you want a minimum of 4 characters, for instance,

System.out.println(String.format("%4d", 5)); // Results in "   5", minimum of 4 characters 
like image 33
I82Much Avatar answered Sep 20 '22 17:09

I82Much