正如标题所说,有一种简单的方法可以在Java中向控制台输出两列吗?
我知道\t
,但在使用printf时,我还没有找到基于特定列的空间方法.
使用宽度和精度说明符,设置为相同的值.这将填充太短的字符串,并截断太长的字符串.' - '标志将左对齐列中的值.
System.out.printf("%-30.30s %-30.30s%n", v1, v2);
我没有使用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");
和输出是
osne two thredsfe one tdsfwo thsdfree onsdfe twdfo three odsfne twsdfo thdfree osdne twdfo three odsfne tdfwo three
迟到的答案,但如果你不想硬编码宽度,那么这样的东西怎么样:
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; } }
由于它在拥有所有线条之前不会打印,因此可以了解制作列的宽度.无需硬编码宽度.