1

Is there a feature that supports using a variable in the flag of javas printf method, for example

printf("%nd", 12);

where n is a variable?

I want to specify spacing outside of the printf method, for example

int n = 5;
System.out.printf("%nd", 12);

Instead of the following

System.out.printf("%5d", 12);

Alternatively, is there any built-in feature similar to that?

4
  • Can you give an example of an input and output you expect? Can you explain your question? Commented Aug 18, 2014 at 16:03
  • Please clarify your specific problem or add additional details to highlight exactly what you need. As currently written, its hard to tell exactly what you're asking. See How do I ask a good question?. Commented Aug 18, 2014 at 16:03
  • Let me edit my question. Commented Aug 18, 2014 at 16:04
  • Have a look now, I edited it. Commented Aug 18, 2014 at 16:09

3 Answers 3

3

You don't need to pass the spacing in as part of the data.
You can just build the format string on the fly in your printf() statement like so:

int n = 5;
System.out.printf("%"+n+"d", 12);
Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect. Good one.
1

Yes . Exists in java System.out.printf("The date is %d/%d/%d", 1,2,1997);

1 Comment

That does not work with a variable as in my example.
0

Use String.format()

Build your format string as required and then pass to String.format(). The use of a format string and argument list is identical to its use in printf()

String myFormat = "...." // build this string with the format you need
String output = String.format( myFormat, ...);

Comments

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.