Max Ringnalda
Max Ringnalda

Reputation: 69

Using variables within printf format section

I've been working with the printf function for a bit now and was wondering if there was a way to use declared variables within the formatting section of printf? Something like:

int x = 5;

System.out.printf("%0xs\n", text);
// Normally this would be "%05s\n"

Meaning that I can use "x" as a changeable variable to be able to change how many 0 it can have. I am asking because I was given a code where the first line will give me a number, which is the amount of 0 I have to put before the text. Is something like this possible?

Upvotes: 0

Views: 415

Answers (1)

Jake Henry
Jake Henry

Reputation: 347

I don't think that you can do it in a singular String.format statement. However I was able to do with nested format.

final int padding = 5;
System.out.printf(String.format("%%0%dd%%n", padding), 7);
System.out.printf(String.format("%%%ds%%n", padding), "hey");

Output:

00007
  hey

Also, you can use %n to insert an end line character automatically.

Upvotes: 2

Related Questions