用于Strings的Java输出格式 [英] Java output formatting for Strings

查看:141
本文介绍了用于Strings的Java输出格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人能告诉我如何使用Java字符串的格式化方法。
例如如果我想所有我的输出的宽度是相同的例如,假设我总是希望我的输出是相同的



>




$职业=学生
状态=单

在这个例子中,所有的输出格式都是整齐排列的,如何使用格式化方法来完成这项工作。

解决方案

编辑:这是一个非常原始的答案,但我不能删除它因为它被接受了。虽然

为什么不只是动态地生成一个空格字符串来插入到语句中。



所以,如果你想让他们都开始在第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屋!

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