0

I am trying to align some text on the right side like so:

String text = "whatever";
System.out.printf("%4s", text);

Except instead of the number 4 in the format scheme I want to use an integer variable, but I cannot find out how to do that. Please help.

What I tried:

int spaceCount = 4;
String text = "whatever";
System.out.printf("%{spaceCount}s", text);
LilGiibb
  • 21
  • 2
  • 4

2 Answers2

2

Java ain't groovy; you have to build up the format old school:

System.out.printf("%" + spaceCount + "s", text);

If you wanted to avoid coding String concatenation, you could format the format:

System.out.printf(String.format("%%%ds", spaceCount), text);
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

As the printf document points out:

A convenience method to write a formatted string to this output stream using the specified format string and arguments.

So it would be easy to achieve the parameterized alignment as:

System.out.printf("%" + spaceCount + "s", "Hello");

Also it mentions:

An invocation of this method of the form out.printf(format, args) behaves in exactly the same way as the invocation: out.format(format, args)

So you can also achieve it as:

System.out.format("%" + spaceCount + "s", "Hello");
Hearen
  • 7,420
  • 4
  • 53
  • 63