Java 的 String.format 方法中的可变宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13785077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 13:58:30  来源:igfitidea点击:

Variable widths in Java's String.format method

javastringstring-formatting

提问by Phillip Huff

I'm working on a project in which I need to display textual trees. I'm trying to use Java's String.format method to simplify the formatting process, but I ran into trouble when trying to apply variable widths.

我正在做一个需要显示文本树的项目。我正在尝试使用 Java 的 String.format 方法来简化格式化过程,但是在尝试应用可变宽度时遇到了麻烦。

Current I have a variable (an int) which is called depth.

当前我有一个称为深度的变量(一个整数)。

I try to do the following:

我尝试执行以下操作:

String.format("%"+depth+"s"," ") + getOriginalText() + "\n";

However I get the following error.

但是我收到以下错误。

java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0

Any suggestions on how to do this, or should I just settle for loops?

关于如何做到这一点的任何建议,还是我应该只解决循环?

Thanks for the help!

谢谢您的帮助!

采纳答案by Yogendra Singh

This works:

这有效:

int depth = 5;
String str= "Hello"+ String.format("%"+depth+"s"," ") + "world" + "\n";
System.out.println(str);

It prints 5 while spaces in between.

它打印 5 而中间有空格。

Hello     World.

你好世界。

Please check you code and make sure that depthis assigned with a valid intvalue. Most likely that (invalid value in depth) is the problem.

请检查您的代码并确保depth分配了有效值int。很可能是(中的无效值depth)是问题所在。

回答by samsam

You could try the following using "System.out.printf" command:

您可以使用“System.out.printf”命令尝试以下操作:

int depth = 10;

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

Hello    World

你好世界