Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing 2d array Java

I am trying print the array I've created below.

NOTE: this is only a portion of my code that I extracted, so any commentary on anything needed before this portion is unnecessary.

String [][]myList = {{"cat", "dog", "mouse"},{"chair", "bench", "stool"}};

for (int i= 0; i < myList.length; i++)
{
    for (int j= 0; j < myList.length; j++)
    {
        System.out.print(myList[i][j]);
    }
}

However, the issue I'm having is that the array print as a list, but I want it to print as:

Cat      chair
Dog      bench
Mouse    stool

Any help would be greatly appreciated.

like image 236
AlexisH Avatar asked Dec 11 '25 16:12

AlexisH


1 Answers

String[][] myList = {{"cat", "dog", "mouse"}, {"chair", "bench", "stool"}};
for (int i = 0; i < myList[0].length; i++) {
    for (int j = 0; j < myList.length; j++) {
        System.out.printf("%-8s", myList[j][i]);
    }
System.out.println();
}

The outer loop (i) iterates through the columns (0, 1, 2). The inner loop (j) iterates through the rows (0 and 1). We use printf to format the output with a width of 8 characters for each element, using %-8s as the format specifier. This ensures that each element is printed in a column of the specified width. After printing each column, we add System.out.println(); to move to the next line to create the desired format.

like image 74
firapinch Avatar answered Dec 14 '25 04:12

firapinch