Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Missing feature in Java 5 printf / format methods

807569Jul 20 2006 — edited Jul 24 2006
Hi,

"Formatted printing for the Java language is heavily inspired by C's printf", says the JavaDoc of java.util.Formatter. However, I can't find one certain sophisticated printf feature which I used to use when I was a C disciple (ohh, long time no C...).

In Java as well as in C,
printf("%-8s", text)
will format a given String text in a width of at least 8 characters, left-justified. Fine. But there are situations (when coding), in which I have no idea how wide, say, a set of strings shall be formatted; the width will turn out at run-time.

In C, I would calculate the width at run-time and pass it to printf as an argument:
printf("%-*s", width, text)
The asterisk formatting character stands for a field width that will be found in the corresponding parameter width. Java does not accept this syntax and starts throwing exceptions.

How can I do that in Java?

Regards,

Two-Bears Friday

Message was edited by:
Two-Bears
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 21 2006
Added on Jul 20 2006
4 comments
136 views