views:

437

answers:

2

As the title says, is there an easy way to output two columns to the console in Java?

I'm aware of /t, but I haven't found a way to space based on a specific column when using printf.

+5  A: 

Use the width and precision specifiers, set to the same value. This will pad strings that are too short, and truncate strings that are too long. The '-' flag will left-justify the values in the columns.

System.out.printf("%-30.30s  %-30.30s%n", v1, v2);
erickson
A: 

So I put together a small test program to demonstrate the formatter and its ability to output text (or numbers) in columns. But it produces ragged output??? Here is the code snippet:

    StringBuilder sb = new StringBuilder();
    // Send all output to the Appendable object sb
    Formatter formatter = new Formatter(sb);
    System.out.printf ("%-10.10s %-10.10s %-10.10s\n", "one", "two", "three\n");
    formatter.format("%-10.10s %-10.10s %-10.10s", "one", "two", "three\n");
    formatter.format("%-10.10s %-10.10s %-10.10s", "one", "two", "three\n");
    formatter.format("%-10.10s %-10.10s %-10.10s", "four", "five", "six\n");
    formatter.format("%-10.10s %-10.10s %-10.10s", "one", "two", "three\n");
    formatter.format("%-10.10s %-10.10s %-10.10s", "four", "five", "six\n");
    System.out.println(sb);

And here is the output produced:

one        two        three
one        two        three
four       five       six
  one        two        three
four       five       six

So whats wrong with the formatting... why dont the columns line up??

Roger