Java Program to format strings into table

Java 8Object Oriented ProgrammingProgramming

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|\n";
      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 |
raja
Published on 14-Dec-2018 16:02:29
Advertisements