0

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?

  • Does this answer your question? [Can one initialize a Java string with a single repeated character to a specific length](https://stackoverflow.com/questions/1900477/can-one-initialize-a-java-string-with-a-single-repeated-character-to-a-specific) – Jesse Sep 13 '22 at 19:48
  • 1
    `System.out.printf("%0"+x+"d%s\n", 0, text)` -- note 0 flag isn't allowed for %s, and even if it were it would be the total for the 0s _and_ the text – dave_thompson_085 Sep 13 '22 at 22:01
  • Ty @dave_thompson_085! Sorry for the late reply but it really solved my issue. – Max Ringnalda Sep 17 '22 at 01:43

1 Answers1

1

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.

Jake Henry
  • 303
  • 1
  • 10