How do I line up multiple values from System.out.print into columns neatly? [duplicate]

StackOverflow https://stackoverflow.com/questions/21917681

  •  14-10-2022
  •  | 
  •  

문제

In Java, how would I line up my file/sizes so that both columns start at the exact same column position?

Here is my code thus far:

System.out.println(child.getName() + " \t\t" + child.length() + " , ");

it makes this output(pic):

enter image description here

However, I would like both columns to line up so that it's like a table-of-contents in a book.

Do I use format-specifierrs?

thanks

도움이 되었습니까?

해결책

System.out.printf("%40s %d,%n",child.getName(),child.length());

Where 40 is the minimum width. Change this as you see fit.

Edit: using %n instead of \n for OS specific linebreak.

다른 팁

Use System.out.printf and specify widths in your format string. Note that in the case of strings that are too long to fit in the column, the formatter will still overflow the specified width.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top