Java:更简单的漂亮打印?
在计算结束时,我打印结果:
System.out.println("\nTree\t\tOdds of being by the sought author");
for (ParseTree pt : testTrees) {
conditionalProbs = reg.classify(pt.features());
System.out.printf("%s\t\t%f", pt.toString(), conditionalProbs[1]);
System.out.println();
}
例如,这会产生:
Tree Odds of being by the sought author
K and Burstner 0.000000
how is babby formed answer 0.005170
Mary is in heat 0.999988
Prelim 1.000000
仅将两个 \t
放入其中有点笨拙 - 列并没有真正对齐。我宁愿有这样的输出:(
Tree Odds of being by the sought author
K and Burstner 0.000000
how is babby formed answer 0.005170
Mary is in heat 0.999988
Prelim 1.000000
注意:我很难让 SO 文本编辑器完美地排列这些列,但希望你明白这个想法。)
有没有一种简单的方法可以做到这一点,或者我必须写尝试根据“树”列中字符串的长度来计算它的方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您正在寻找字段长度。尝试使用这个:
-32告诉你字符串应该左对齐,但字段长度为32个字符(根据你的喜好调整,我选择32,因为它是8的倍数,这是一个正常的制表位终端)。在标题上使用相同的内容,但使用
%s
而不是%f
也会使该排列很好。You're looking for field lengths. Try using this:
The -32 tells you that the string should be left justified, but with a field length of 32 characters (adjust to your liking, I picked 32 as it is a multiple of 8, which is a normal tab stop on a terminal). Using the same on the header, but with
%s
instead of%f
will make that one line up nicely too.您需要的是令人惊叹且免费的
format()
。它的工作原理是让您在模板字符串中指定占位符;它产生模板和值的组合作为输出。
示例:
%s
是字符串的占位符;%25s
表示将任何给定字符串空白填充到 25 个字符。%-25s
表示将字段中的字符串左对齐,即填充到字符串的右侧。%9.7f
表示输出一个浮点数,共9位,小数点右边7位。%n
是“执行”行终止所必需的,否则当您从System.out.println()
转到System 时,您会错过这一点.out.format()。
或者,您可以使用
创建一个输出字符串,然后
像以前一样使用它来打印它。
What you need is the amazing yet free
format()
.It works by letting you specify placeholders in a template string; it produces a combination of template and values as output.
Example:
%s
is a placeholder for Strings;%25s
means blank-pad any given String to 25 characters.%-25s
means left-justify the String in the field, i.e. pad to the right of the string.%9.7f
means output a floating-point number with 9 places in all and 7 to the right of the decimal.%n
is necessary to "do" a line termination, which is what you're otherwise missing when you go fromSystem.out.println()
toSystem.out.format()
.Alternatively, you can use
to create an output String, and then use
as before to print it.
如何
查看文档有关格式化程序迷你语言。
How about
See the docs for more information on the Formatter mini-language.
http://java.sun.com/ j2se/1.5.0/docs/api/java/text/MessageFormat.html
http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html
使用 j-text-utils 您可以打印来控制台如下表格:
就这么简单:
API 还允许排序和行编号...
Using j-text-utils you may print to console a table like:
And it as simple as:
The API also allows sorting and row numbering ...
也许
java.io.PrintStream
的printf
和/或format
方法就是您正在寻找的...Perhaps
java.io.PrintStream
'sprintf
and/orformat
method is what you are looking for...