4

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?

2 Answers 2

7

Use StringUtils.center from the Commons Lang library:

StringUtils.center(column, "Column Heading".length());
Sign up to request clarification or add additional context in comments.

Comments

4

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");

3 Comments

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)
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.
Thanks. As a C programmer from decades past, I was trying to get the * to work -- and some blog out there says it should work. This is an almost too obvious workaround that I somehow couldn't come up with. =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.