Java的String.format方法中的可变宽度 [英] Variable widths in Java's String.format method

查看:741
本文介绍了Java的String.format方法中的可变宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

当前我有一个变量(一个int),称为深度。

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

我尝试执行以下操作:

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

但是我收到以下错误。

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

有关如何执行此操作的任何建议,或者我应该解决循环问题?

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

感谢您的帮助!

推荐答案

这有效:

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

它打印5而其间有空格。

It prints 5 while spaces in between.


Hello      World。

Hello     World.

请检查您的代码并确保 depth 已分配有效 int value。最有可能的是(深度中的无效值)是问题。

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.

这篇关于Java的String.format方法中的可变宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆