回答得晚了,但是如果你不想硬编码宽度,那么这样的功能如何:
public static void main(String[] args) {
new Columns()
.addLine("One", "Two", "Three", "Four")
.addLine("1", "2", "3", "4")
.print()
;
}
并显示:
One Two Three Four
1 2 3 4
好吧,只需要:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Columns {
List> lines = new ArrayList<>();
List 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 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;
}
}
因为它只有所有的行才能打印,所以它可以了解列的宽度。不需要硬编码宽度。