字符串的 Java 输出格式 [英] Java output formatting for Strings
问题描述
我想知道是否有人可以向我展示如何使用 Java 字符串的格式方法.例如,如果我希望所有输出的宽度相同
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
在这个例子中,所有的输出都整齐地排列在彼此之下;我将如何使用 format 方法完成此操作.
In this example, all the output are neatly formatted under each other; How would I accomplish this with the format method.
推荐答案
这是一个非常原始的答案,但我无法删除它,因为它已被接受.请参阅下面的答案以获得更好的解决方案
为什么不直接生成一个空白字符串来插入到语句中.
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.
所以如果你想让它们都从第 50 个字符开始......
So if you want them all to start on the 50th character...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob
";
System.out.println(key+space+value);
将所有这些放在一个循环中,并在每次迭代之前初始化/设置键"和值"变量,您就大功告成了.我也会使用 StringBuilder
类,这样效率更高.
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.
这篇关于字符串的 Java 输出格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!