简体   繁体   English

Java:如何使用变量正确对正文本

[英]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. 除了要使用格式方案中的数字4之外,我想使用一个整数变量,但是我找不到解决方法。 Please help. 请帮忙。

What I tried: 我试过的

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

Java ain't groovy; Java不是俗套的; 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: 正如printf文档指出的那样:

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) 形式out.printf(格式,参数)的这种方法的调用行为以完全相同的方式调用: out.format(format, args)

So you can also achieve it as: 因此,您也可以通过以下方式实现它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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