Java 字符串输出格式
我想知道是否有人可以向我展示如何使用 Java 字符串的格式化方法。 例如,如果我希望所有输出的宽度相同
例如,假设我总是希望我的输出相同
Name = Bob
Age = 27
Occupation = Student
Status = Single
在此示例中,所有输出都整齐地格式化在一起;我将如何使用格式方法来实现这一点。
I was wondering if someone can show me how to use the format method for Java Strings.
For instance If I want the width of all my output to be the same
For instance, Suppose I always want my output to be the same
Name = Bob
Age = 27
Occupation = Student
Status = Single
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
输出如下所示:
作为参考,我推荐 格式化程序语法的 Javadoc
The output looks like this:
As a reference I recommend Javadoc on formatter syntax
例如,如果您想要至少 4 个字符,
If you want a minimum of 4 characters, for instance,
要回答您更新的问题,您可以
打印
To answer your updated question you can do
prints
编辑:这是一个非常原始的答案,但我无法删除它,因为它已被接受。请参阅下面的答案以获得更好的解决方案,但
为什么不动态生成一个空白字符串以插入到语句中呢?
因此,如果您希望它们全部从第 50 个字符开始...
将所有这些放入一个循环中,并在每次迭代之前初始化/设置“键”和“值”变量,这样您就成功了。我也会使用 StringBuilder 类,它更有效。
EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though
Why not just generate a whitespace string dynamically to insert into the statement.
So if you want them all to start on the 50th character...
Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the
StringBuilder
class too which is more efficient.对于十进制值,您可以使用 DecimalFormat
,输出将为:
有关更多详细信息,请参见此处:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
For decimal values you can use DecimalFormat
and output will be:
For more details look here:
http://docs.oracle.com/javase/tutorial/java/data/numberformat.html