简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM