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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With