1

Possible Duplicate:
Java printf using variable field size?

I haven't worked with Java in a while so I was looking for a way to specify variable width in format/printf when formatting/printing output. My example shows the use with an integer, but of course I'd like this to work for other types too.

E.g., something along the lines of

int val = 8;
int wid = 5;

System.out.printf("%"*d\n", wid, val);  

I could use this work-around, which is ugly:

System.out.printf("%"+wid+"d\n", val);

Was the * variable field width specifier removed from Java? This old'ish page, section 1.3.1, shows the use (like it would be used in C), but I can't get it to work, resulting in:

java.util.UnknownFormatConversionException: Conversion = '*'

nor have I been able to find more recent references that this does work.

Is there an easier way to do this other than my work-around above?

I did look around before posting and came across this about 2-year old SO question Java printf using variable field size? but is that the final word on this?

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191

1 Answers1

0

The general syntax of a format specifier is

%[parameter][flags][width][.precision][length]type

Instead of printf, you can also use

String.format("%"+wid+"d",val);

And yes, these are the only ways in case you are using a Java Formatter.

Arham
  • 2,072
  • 2
  • 18
  • 30