eri*_*son 54
使用宽度和精度说明符,设置为相同的值.这将填充太短的字符串,并截断太长的字符串.' - '标志将左对齐列中的值.
System.out.printf("%-30.30s %-30.30s%n", v1, v2);
Run Code Online (Sandbox Code Playgroud)
gti*_*333 25
我没有使用Formatter类就做了:
System.out.printf("%-10s %-10s %-10s\n", "osne", "two", "thredsfe");
System.out.printf("%-10s %-10s %-10s\n", "one", "tdsfwo", "thsdfree");
System.out.printf("%-10s %-10s %-10s\n", "onsdfe", "twdfo", "three");
System.out.printf("%-10s %-10s %-10s\n", "odsfne", "twsdfo", "thdfree");
System.out.printf("%-10s %-10s %-10s\n", "osdne", "twdfo", "three");
System.out.printf("%-10s %-10s %-10s\n", "odsfne", "tdfwo", "three");
Run Code Online (Sandbox Code Playgroud)
和输出是
osne two thredsfe
one tdsfwo thsdfree
onsdfe twdfo three
odsfne twsdfo thdfree
osdne twdfo three
odsfne tdfwo three
Run Code Online (Sandbox Code Playgroud)
can*_*nge 12
迟到的答案,但如果你不想硬编码宽度,那么这样的东西怎么样:
public static void main(String[] args) {
new Columns()
.addLine("One", "Two", "Three", "Four")
.addLine("1", "2", "3", "4")
.print()
;
}
Run Code Online (Sandbox Code Playgroud)
并显示:
One Two Three Four
1 2 3 4
Run Code Online (Sandbox Code Playgroud)
所需要的只是:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Columns {
List<List<String>> lines = new ArrayList<>();
List<Integer> maxLengths = new ArrayList<>();
int numColumns = -1;
public Columns addLine(String... line) {
if (numColumns == -1){
numColumns = line.length;
for(int column = 0; column < numColumns; column++) {
maxLengths.add(0);
}
}
if (numColumns != line.length) {
throw new IllegalArgumentException();
}
for(int column = 0; column < numColumns; column++) {
int length = Math
.max(
maxLengths.get(column),
line[column].length()
)
;
maxLengths.set( column, length );
}
lines.add( Arrays.asList(line) );
return this;
}
public void print(){
System.out.println( toString() );
}
public String toString(){
String result = "";
for(List<String> line : lines) {
for(int i = 0; i < numColumns; i++) {
result += pad( line.get(i), maxLengths.get(i) + 1 );
}
result += System.lineSeparator();
}
return result;
}
private String pad(String word, int newLength){
while (word.length() < newLength) {
word += " ";
}
return word;
}
}
Run Code Online (Sandbox Code Playgroud)
由于它在拥有所有线条之前不会打印,因此可以了解制作列的宽度.无需硬编码宽度.
归档时间: |
|
查看次数: |
72105 次 |
最近记录: |