Music Lover
Music Lover

Reputation: 33

Display a second output horizontally but first output vertically

can anyone help me out how to make my second output display horizontally but not the first....

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

I want a display look like this:

enter image description here

And the actual result give me like this:

enter image description here

Upvotes: 1

Views: 39

Answers (1)

laune
laune

Reputation: 31300

You need to compute the dimensions first so you can format the columns properly: maxwidths. Noting the maximum number of rows helps for controlling the printing part.

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

Upvotes: 2

Related Questions