Formatting output with the same number of columns

I want to create something like this, where each line is surrounded by a "pipe" char.

| First Line | | 100 200 | | 1000 2000 | 
  • In the first line, the right filling is 1 space.
  • In the second line, the correct filling is 4 spaces.
  • The third line contains 2 spaces.

I am trying to do this with printf + formating (and not explicitly calculating the fill number), but I am having some problems with the syntax of the formation. Here is my current code:

 System.out.printf("| FIRST LINE" + "%50s\n", "|"); System.out.printf("| 100 200" + "%50s", "|"); System.out.printf("| 1000 2000" + "%50s", "|"); 

I am trying to indicate that the maximum per line is 50 characters, which is the first character in the string "pipe" and the last character in the string is another "pipe").

The problem is that 50 spaces are placed without considering the characters already in use on the left side (that is, "| FIRST LINE"). The above code is similar to:

 System.out.format("%s %50s\n", "| FIRST LINE", "|"); 

So, how can I define the output format so that both lines are counted for the width?

Thanks in advance.

+4
source share
3 answers

Try Formatter .

eg.

 StringBuffer sb = new StringBuffer(); Formatter f = new Formatter(sb, Locale.getDefault()); f.format("| %-50s |%n", "FIRST LINE"); f.format("| %-50s |%n", "200 100"); f.format("| %-50s |%n", "1000 2000"); String finalResult = sb.toString(); System.out.println(finalResult); 

Output:

  |  FIRST LINE |
 |  200 100 |
 |  1000 2000 |
+6
source

You can use StringBuilder . It has methods for setting characters and replacing strings. First create a StringBuilder and fill it with characters containing spaces and end of lines. Then place the pipe symbol in the right place. Finally, replace the spaces in the middle with a formatted string. Remember to count the newline characters or make the specified line of methods for the string and add the lines together using another StringBuilder.

0
source

Something that automatically selects the padding equal to the longest line plus two characters (for example, FIRST LINE | above) is impossible, but it would be pretty neat.

The best I can help you with is this:

  System.out.println(String.format("| %10s |", "FIRST LINE" )); System.out.println(String.format("| %10s |", "100 200" )); System.out.println(String.format("| %10s |", "1000 2000" )); 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1390132/


All Articles