Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Easier pretty printing?

At the end of my computations, I print results:

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

This produces, for instance:

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

Just putting two \t in there is sort of clumsy - the columns don't really line up. I'd rather have an output like this:

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

(note: I'm having trouble making the SO text editor line up those columns perfectly, but hopefully you get the idea.)

Is there an easy way to do this, or must I write a method to try to figure it out based on the length of the string in the "Tree" column?

like image 752
Nick Heiner Avatar asked Dec 09 '09 18:12

Nick Heiner


2 Answers

You're looking for field lengths. Try using this:

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

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.

like image 129
falstro Avatar answered Nov 20 '22 20:11

falstro


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:

System.out.format("%-25s %9.7f%n", "K and Burstner", 0.055170);
  • %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 from System.out.println() to System.out.format().

Alternatively, you can use

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

to create an output String, and then use

System.out.println(outputString);

as before to print it.

like image 4
Carl Smotricz Avatar answered Nov 20 '22 20:11

Carl Smotricz