java 如何打印垂直对齐的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3177697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print vertically aligned text
提问by razor35
I want to print an output of the following format in a file..
我想在文件中打印以下格式的输出..
1 Introduction 1
1.1 Scope 1
1.2 Relevance 1
1.2.1 Advantages 1
1.2.1.1 Economic 2
1.2.2 Disadvantages 2
2 Analysis 2
I cannot get the page numbers to align vertically in a line. How to do this??
我无法让页码在一行中垂直对齐。这个怎么做??
回答by polygenelubricants
You need to left-justify the first column, and right-justify the second column.
您需要左对齐第一列,右对齐第二列。
Here's an example:
下面是一个例子:
String[] titles = {
"1 Introduction",
" 1.1 Scope",
" 1.2 Relevance",
" 1.2.1 Advantages",
" 1.2.1.1 Economic",
" 1.2.2 Disadvantages",
"2 Analysis",
};
for (int i = 0; i < titles.length; i++) {
System.out.println(String.format("%-30s %4d",
titles[i],
i * i * i // just example formula
));
}
This prints (as seen on ideone.com):
这打印(如在 ideone.com 上看到的):
1 Introduction 0
1.1 Scope 1
1.2 Relevance 8
1.2.1 Advantages 27
1.2.1.1 Economic 64
1.2.2 Disadvantages 125
2 Analysis 216
The format %-30s %4dleft-justifies (-flag) the first argument with width of 30, and right-justifies the second argument with width of 4.
格式%-30s %4d左对齐 ( -flag) 宽度为 30 的第一个参数,右对齐宽度为 4 的第二个参数。
API links
接口链接
回答by Kilian Foth
Usually, with a String format specifier that enforces a minimum width:
通常,使用强制最小宽度的字符串格式说明符:
someStream.write(String.format("%60s %3d", sectionName, pageNumber));

