Java printf using variable field size?

Posted by paxdiablo on Stack Overflow See other posts from Stack Overflow or by paxdiablo
Published on 2010-03-31T02:41:31Z Indexed on 2010/03/31 4:33 UTC
Read the original article Hit count: 392

Filed under:
|
|
|

I'm just trying to convert some C code over to Java and I'm having a little trouble with String.printf.

In C, to get a specific width based on a variable, I can use:

printf("Current index = %*d\n", sz, index);

and it will format the integer to be a specific size based on sz.

Trying:

System.out.println(String.format("Current index = %*d\n", sz, index));

results in an error since it doesn't like the *.

I currently have the following kludge:

System.out.println(String.format("Current index = %" + sz + "d\n", index));

but I'm hoping there's a slightly better way, yes?

© Stack Overflow or respective owner

Related posts about java

Related posts about printf