0

With printf I can decide how many space characters should be before the variable i that I want to print. In the example below, it is 10. Is it possible to have there a variable instead of the number 10? So that the spaces characters depend on the value of a variable?

System.out.printf("%10d" , i);
0

2 Answers 2

2

The format string is still a string, so assuming a width variable System.out.printf("%" + width + "d", x); does the trick.

So for example

var width = 10; var x = 123;
System.out.printf("%" + width + "d", x);

prints 123 (7 leading spaces + 3 digits = 10), while

var width = 3; var x = 123;
System.out.printf("%" + width + "d", x);

prints 123

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

1 Comment

It's annoying that Java didn't adopt "%*d" (etc) from C's printf.
0

Define a lambda to create the desired width and then call that prior to printing the value.

Function<Integer, String> format = width-> "%%%dd\n".formatted(width);
int x = 4567;
System.out.printf(format.apply(10),x); 
System.out.printf(format.apply(5),x);
// or create it once for multiple printf calls.
String form = format.apply(3);
System.out.printf(form, 2);
System.out.printf(form, 4);

prints

      4567
 4567
  2
  4
  • %%%dd - the first % escapes the second so on the last %d formats the width value.
  • then that format string is returned and used to format the supplied argument in the printf statement

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.