Search code examples
javaprintfmagic-numbers

Losing magic numbers in Java printf format specifiers to generate columns


In C, the printf function has a great wildcard feature, where you can use an asterisk where you would normally place an int that specifies minimum column width. So you can go

#DEFINE COL_WIDTH 20;  

up in the preprocessor directives, and then later you can put

printf("%*s", COL_WIDTH, myString);

to print myString in a 20 character column.

This asterisk trick doesn't seem to be implemented in Java. I have to go

printf("%20s", myString); 

instead. This is a flagrant magic number, especially if you are trying to use printf to do something like build a table where you want an easy way to change the column width on a lot of lines at once. So,

  • is there something I'm missing about printf in Java that makes what I want to do possible, or

  • is there a neat and more Java-like way of formatting text for output in a table without using magic numbers?


Solution

  • printf("%"+COL_WIDTH+"s", myString);