水平显示第二个输出,但首先垂直输出

时间:2017-12-11 10:45:29

标签: java multidimensional-array

任何人都可以帮我解决如何使我的第二个输出水平显示但不是第一个......

public static void main(String[] args) {

    String[][][] storage = 
    {//root
        {//nested
            { "Name","Gender","Address","Age","Birth"}, //contains
            { "Consumer","Vendor","IDE","Certified"}
        },
        {
            { "Month","Year","Day"}, //contains
            { "Hours","Minutes","Seconds","Milli","Nano"},
            { "Decade","Century"},
            { "Water","Earth","Fire","Lightning"}
        },
        {
            { "Good","Bad","Strong","Weak"}, //contains
            { "Polite","Honest","Gentle","Courage","Kind"},
            { "Kilos","Grams","Tons","Pounds"}
        }
    };

    for (int i=0; i<=storage.length-1; i++){
        System.out.println(i);
        for (String[] inner : storage[i]){
            for (String normal : inner){
                System.out.print(normal+" ");
            }
            System.out.println();
        }
    }

我希望显示器看起来像这样:

enter image description here

实际结果就像这样:

enter image description here

1 个答案:

答案 0 :(得分:2)

您需要先计算尺寸,以便正确格式化列:maxwidths。注意最大行数有助于控制打印部件。

int maxrow = 0;
List<Integer> maxwidths = new ArrayList<>();
for (int i=0; i<=storage.length-1; i++){
    int maxwidth = 0;
    for (String[] inner : storage[i]){
        int width = String.join( " ", inner ).length();
        if( width > maxwidth ) maxwidth = width;
    }
    if( storage[i].length > maxrow ) maxrow = storage[i].length;
    maxwidths.add( maxwidth );
}

for (int i=0; i<=storage.length-1; i++){
    System.out.printf( "%-" + maxwidths.get(i) + "d ", i );
}
System.out.println();
for( int row = 0; row < maxrow; ++row ){
    for (int i=0; i<=storage.length-1; i++){
        String normal;
        if( row < storage[i].length ){
            normal = String.join( " ", storage[i][row] );
        } else {
            normal = "";
        }
        System.out.printf( "%-" + maxwidths.get(i) + "s ", normal );
    }
    System.out.println();
}