Home > other >  Printf in Java with variable spaces before the output
Printf in Java with variable spaces before the output

Time:02-05

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("d" , i);

CodePudding user response:

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

CodePudding user response:

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

Function<Integer, String> format = width-> "%%           
  • Related