Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

command line - Java println formatting so I can display a table?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...