Variable widths in Java's String.format method

喜欢而已 提交于 2019-12-01 16:05:01

问题


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.

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!


回答1:


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.

Hello     World.

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



来源:https://stackoverflow.com/questions/13785077/variable-widths-in-javas-string-format-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!