Aaron Schif
Aaron Schif

Reputation: 2442

Java printf specify variable width

I have this simplified code:

System.out.printf("%-*s   Exam Percentage: %4.1f   Final Grade: %c\n", VAR, "fox"+", "+"jim",25.3225, 'C');

Which, according to this and other resources, should produce a column 'VAR' characters wide to the effect of:

 fox, jim   Exam Percentage:  25.3    Final Grade: C

It runs through a for loop and VAR is the largest size of the first string.

I reconize the method:

System.out.printf("%-"+VAR+"s   Exam Percentage: %4.1f   Final Grade: %c\n", "fox"+", "+"jim",25.3225, 'C');

It works, but I am mainly curious. Also, the afore mentioned page mentions 'argsize' an explanation into that may provide some insight.

P.S. I know the the code has literals. Its for simplicity.

Upvotes: 3

Views: 2206

Answers (1)

minopret
minopret

Reputation: 4806

Format strings for method printf of a java.io.PrintStream such as System.out are defined as Java format strings. They differ from the documentation you linked which is for something called Lava. In particular the width for a percent-conversion in Java is a number and cannot be replaced by an asterisk (*). In other words, as you noticed, it's not OK to write %-*s but it is OK to write %-20s or whatever your preferred number is.

Upvotes: 1

Related Questions