LilGiibb
LilGiibb

Reputation: 21

Java: How to right justify text, with Variable

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);

Upvotes: 0

Views: 3784

Answers (2)

Hearen
Hearen

Reputation: 7838

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");

Upvotes: 0

Bohemian
Bohemian

Reputation: 425198

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);

Upvotes: 3

Related Questions