Java println 格式化以便我可以显示表格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1358512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java println formatting so I can display a table?
提问by
How can I utilize System.out.print(ln/f)
in a way that will allow me to format my output into a table?
我怎样才能System.out.print(ln/f)
以一种允许我将输出格式化为表格的方式使用?
If I'm to use printf
, what formatting should I specify to achieve the below results?
如果我要使用printf
,我应该指定什么格式来实现以下结果?
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?
一切都排列整齐漂亮?
采纳答案by erickson
Yes, since Java 5, the PrintStream
class used for System.out
has the printf
method, so that you can use string formatting.
是的,从 Java 5 开始,PrintStream
用于的类System.out
具有printf
方法,因此您可以使用字符串格式。
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);
回答by Eric
you can println("\t")
which prints a tab, it will align everything easily.
你可以println("\t")
打印一个标签,它会很容易地对齐所有东西。