10

在我的计算结束时,我打印结果:

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 文本编辑器完美地排列这些列,但希望你能明白。)

有没有一种简单的方法可以做到这一点,或者我必须编写一个方法来尝试根据“树”列中字符串的长度来计算它?

4

6 回答 6

15

您正在寻找字段长度。尝试使用这个:

printf ("%-32s %f\n", pt.toString(), conditionalProbs[1])

-32 告诉您字符串应该左对齐,但字段长度为 32 个字符(根据您的喜好调整,我选择了 32,因为它是 8 的倍数,这是终端上的正常制表位)。在标题上使用相同的内容,但使用%s而不是%f会使那一个也很好地排列。

于 2009-12-09T18:45:55.627 回答
4

您需要的是令人惊叹且免费的format()

它通过让您在模板字符串中指定占位符来工作;它产生模板和值的组合作为输出。

例子:

System.out.format("%-25s %9.7f%n", "K and Burstner", 0.055170);
  • %s是字符串的占位符;
  • %25s表示将任何给定的字符串空白填充到 25 个字符。
  • %-25s表示将字段中的字符串左对齐,即填充到字符串的右侧。
  • %9.7f表示输出一个浮点数,总共有 9 位,小数点右边 7 位。
  • %n“做”一个行终止是必要的,这是你从System.out.println()到时所缺少的System.out.format()

或者,您可以使用

String outputString = String.format("format-string", arg1, arg2...);

创建一个输出字符串,然后使用

System.out.println(outputString);

像以前一样打印它。

于 2009-12-09T18:51:43.950 回答
2

怎么样

System.out.printf("%-30s %f\n", pt.toString(), conditionalProbs[1]);

有关Formatter 迷你语言的更多信息,请参阅文档。

于 2009-12-09T18:46:29.420 回答
1

http://java.sun.com/j2se/1.5.0/docs/api/java/text/MessageFormat.html

于 2009-12-09T18:45:17.827 回答
1

使用j-text-utils您可以打印到控制台,例如:

它很简单:

TextTable tt = new TextTable(columnNames, data);                                                         
tt.printTable();   

该 API 还允许排序和行编号...

于 2013-12-25T10:38:38.813 回答
0

也许java.io.PrintStream'sprintf和/或formatmethod 是您正在寻找的...

于 2009-12-09T18:54:03.540 回答