如何使用System.out.format();所以答案看起来像那样?

时间:2013-07-08 11:06:35

标签: java

 String[] B= {"2","14","5","12","10"};
 String[] I= {"20","25","18","16","22"};
 String[] N= {"42","32","FREE","31","39"};
 String[] G= {"60","55","53","46","59"};
 String[] O= {"64","70","67","75","71"};

 System.out.format();
}

}

预期答案:

B         I             N            G            O 
2         20            42           60           64
14        25            32           55           70
5         18            FREE         53           67
12        16            31           46           75
10        22            39           59           71

2 个答案:

答案 0 :(得分:1)

解决方案是使用%-<n>s,其中<n>是您所需的“列”长度:

System.out.printf("'%-8s%-8s'\n", "hello", "world");

给出:

'hello   world   '

请注意,更一般地说,您可以使用Formatter。这是printf()使用的内容。

答案 1 :(得分:0)

您可以使用此代码

获得预期的结果
    String[] B = {"2", "14", "5", "12", "10"};
    String[] I = {"20", "25", "18", "16", "22"};
    String[] N = {"42", "32", "FREE", "31", "39"};
    String[] G = {"60", "55", "53", "46", "59"};
    String[] O = {"64", "70", "67", "75", "71"};

    String[][] test={B,I,N,G,O};
    int n=0;
    System.out.println("B  I  N  G  O");
    for(String[] str:test){
         for(int i=0;i<str.length;i++){
             System.out.print(test[i][n] + " ");
         }
        System.out.println("\n");
        n++;
    }