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?

3
  • Does this answer your question? Can one initialize a Java string with a single repeated character to a specific length Commented Sep 13, 2022 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 Commented Sep 13, 2022 at 22:01
  • Ty @dave_thompson_085! Sorry for the late reply but it really solved my issue. Commented Sep 17, 2022 at 1:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

%n is either LF or CRLF depending on platform; this may actually be better, or worse, but it is not the same as just \n.
Correct. I figured I would mention it since OP is simply printing to the console.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.