tags:

views:

668

answers:

3

I'm creating an output in Java using printf() to create table headers. One of the columns needs variable width.

Basically it should look like this:

//two coords
Trial    Column Heading
1        (20,30)(30,20)
//three coords
Trial        Column Heading
1        (20,40)(50,10)(90,30)

I tried to use:

int spacing = numCoords * 7; //size of column
printf("Trial    %*^s", column, "Column Heading");

But I keep getting output errors when I try to use * or ^ in the conversion statement.

Does anyone have any idea what the correct formatting string should be?

A: 

In Java, use System.out.println()

According to your requirements, You should be using something like,

System.out.println("Trial"+getSpacer(spacing)+"Column Heading");

Here getSpacer(int spaces) will return you a String with that many number of spaces you want.

Bragboy
A: 

Java does not support the "*" format specifier. Instead, insert the width directly into the format string:

int spacing = numCoords * 7; //size of column
System.out.printf("Trial    %" + spacing + "s", "Column Heading");
bkail
OK, this makes sense, except the output isn't centered, it would be aligned right, correct? (There are more columns, so it needs to either be centered or have equal spacing on each side)
Khan
Indeed. ((spacing + "Column Heading") / 2) would do that, I think.By the way, if you find an answer you like (this one or someone else's), you should accept it to grant points.
bkail
+1  A: 

Use StringUtils.center from the Commons Lang library:

StringUtils.center(column, "Column Heading".length());
Bytecode Ninja
This seems to be the best solution, it's a shame it needs a new library...
Khan