Using printf to pad spaces
Hi there - i have just a quick question regarding printf
I'm try to pad numbers into a certain size.
eg if i had a number like 118
It would look like this:
System.out.printf("%6s", "118");
Sure that puts 118 on the right side like this:
'XXX118'
But i want the statement to take in a variable pad size that will pad accordingly.
eg. it could be 3, 8 or 7 for example.
Could i use something like this: (btw the 8 is just a test value - 6 could be any number)
System.out.printf("%*s", "118", 8);
Exception in thread "main" java.util.UnknownFormatConversionException: Conversion = '*'
Unfortunately the compiler doesnt like this. In a previous post i found that i had openJDK now i am using Oracle's own jdk
I can't see why "%*s" doesnt take the 8 in for *. I read from an old post that "%*s" would work.
The output with 8 would look like:
'XXXXX118'
X in place for blanks for the benefit of this post.
Thanks,
Hamster
Re: Using printf to pad spaces
Read the API documentation for the Formatter class and you'll find that (sadly enough) you can't specify the width of a field with the '*' character; that's a C-ism; but nothing forbids you from constructing your own format String; e.g.
Code:
int width= ...;
String format= "%"+width+"s";
System.out.printf(format, "118");
kind regards,
Jos
Re: Using printf to pad spaces
That's neat - thank you. I'll remember that for next time when the default doesnt have the option. :D
Let me try that.