Search code examples
javaconsolepretty-print

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?


Solution

  • 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.