有一种简单的方法可以在Java中将两列输出到控制台吗?

时间:2009-03-31 03:08:43

标签: java

正如标题所说,有一种简单的方法可以用Java输出两列到控制台吗?

我知道\t,但在使用printf时,我没有找到基于特定列的空间方法。

3 个答案:

答案 0 :(得分:53)

使用宽度和精度说明符,设置为相同的值。这将填充太短的字符串,并截断太长的字符串。 ' - '标志将左对齐列中的值。

System.out.printf("%-30.30s  %-30.30s%n", v1, v2);

答案 1 :(得分: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");

,输出

osne       two        thredsfe  
one        tdsfwo     thsdfree  
onsdfe     twdfo      three     
odsfne     twsdfo     thdfree   
osdne      twdfo      three     
odsfne     tdfwo      three     

答案 2 :(得分:12)

迟到的回答但是如果你不想对宽度进行硬编码,那么这样的事情怎么样:

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<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;
    }
}

由于它不会打印直到它包含所有行,因此它可以了解制作列的宽度。无需硬编码宽度。