views:

137

answers:

2

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?

+1  A: 

For $20 USD you can buy this jar:

http://sharkysoft.com/software/java/lava3/printf/purchase/

You can evaluate it for free first under its GPL license:

http://sharkysoft.com/software/java/lava3/printf/download/current/lava3-printf-jar.zip

If I were porting a bunch of C code I think I would just shell out the $20. The license permits unlimited distribution to end-users.

(Full disclosure: I have no relationship with sharkysoft, I have never tried the jar, and I do not profit in any way from linking to them.)

Julius Davies
Actually, for $20, I'd rather buy a good bottle of red and use my kludge :-) I thought there may be a standard way to do it with format strings but it's looking more and more unlikely as I investigate further (it's not so much the $20 I'm worried about, that's chicken-feed, it's the bureaucracy I'll have to go through to be able to use it). Thanks for the tip, I'll leave it open for a couple of days in case something comes up.
paxdiablo
+1  A: 
matsev