13

How can I utilize System.out.print(ln/f) in a way that will allow me to format my output into a table?

If I'm to use printf, what formatting should I specify to achieve the below results?

Example table I'd like to print:

n       result1      result2      time1      time2    
-----------------------------------------------------  
 5      1000.00      20000.0      1000ms     1250ms
 5      1000.00      20000.0      1000ms     1250ms
 5      1000.00      20000.0      1000ms     1250ms

With everything lined up nice and pretty?

GEOCHET
  • 20,745
  • 15
  • 72
  • 98

2 Answers2

25

Yes, since Java 5, the PrintStream class used for System.out has the printf method, so that you can use string formatting.


Update:

The actual formatting commands depend on the data you are printing, the exact spacing you want, etc. Here's one of many possible examples:

System.out.printf("%1s  %-7s   %-7s   %-6s   %-6s%n", "n", "result1", "result2", "time1", "time2");
System.out.printf("%1d  %7.2f   %7.1f   %4dms   %4dms%n", 5, 1000F, 20000F, 1000, 1250);
System.out.printf("%1d  %7.2f   %7.1f   %4dms   %4dms%n", 6, 300F, 700F, 200, 950);
erickson
  • 257,800
  • 54
  • 385
  • 479
4

you can println("\t") which prints a tab, it will align everything easily.

dimo414
  • 44,897
  • 17
  • 143
  • 228
Eric
  • 19,040
  • 18
  • 80
  • 143
  • 5
    Not if the values have different lengths. – Outlaw Programmer Aug 31 '09 at 18:09
  • While `\t` isn't perfect, many terminals will format tabs as a variable-spaced element, letting you easily align similar data into columns. Even better, spreadsheet programs like Excel can easily parse tab-separated data (TSV) - personally, I find the format more readable and easier to work with than the more common comma-separated (CSV). – dimo414 Jul 07 '14 at 02:34