Java Program to format strings into table



To format strings into table, use the System.out.format.

For our table, we have given 15s, that means 15 spaces. In the same way for the second column after the indices.

|%1$-15s|%2$-15s|

Added the above in a string, so that we don’t have add it again and again.

The following is an example.

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String strFormat = "|%1$-15s|%2$-15s|
";       System.out.format(strFormat, "One", "Two");       System.out.format(strFormat, "Three", "Four");       System.out.format(strFormat, "Five", "Six");       System.out.format(strFormat, "Seven", "Eight");       System.out.format(strFormat, "Nine", "Ten");       System.out.format(strFormat, "Eleven", "Twelve");       System.out.format(strFormat, "Thirteen", "Fourteen");       System.out.format(strFormat, "Fifteen", "Sixteen");    } }

Output

|One |Two |
|Three |Four |
|Five |Six |
|Seven |Eight |
|Nine |Ten |
|Eleven |Twelve |
|Thirteen |Fourteen |
|Fifteen |Sixteen |
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements