用于Strings的Java输出格式 [英] Java output formatting for Strings
问题描述
例如如果我想所有我的输出的宽度是相同的例如,假设我总是希望我的输出是相同的
>
$职业=学生
状态=单
在这个例子中,所有的输出格式都是整齐排列的,如何使用格式化方法来完成这项工作。
编辑:这是一个非常原始的答案,但我不能删除它因为它被接受了。虽然
为什么不只是动态地生成一个空格字符串来插入到语句中。
所以,如果你想让他们都开始在第50个字符... ... $ / b>
String key =Name =;
String space =;
for(int i; i <(50-key.length); i ++)
{space = space +;}
String value =Bob\\\
;
System.out.println(key + space + value);
把所有这些放在一个循环中,然后初始化/设置key和value变量每次迭代,你是金。我也会使用 StringBuilder
类,这样更高效。
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.
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...
String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);
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.
这篇关于用于Strings的Java输出格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!