Jeff Ogah Jeff Ogah -4 years ago 88
Java Question

Java- How to use For Loop with (Multidimensional) Array of Strings

I was able to use for loop with int multidimensional arrays but I'm unable to reproduce it with multi arrays.

public class array {

public static void main(String[] args) {
String[][] words = new String[2][3];
words[0][0] = "a";
words[0][1] = "b";
words[0][2] = "c";
words[1][0] = "d";
words[1][1] = "e";
words[1][2] = "f";
}
}


Would love some help on how to iterate that

For reference, this was what I did for int

int[][] multi = {
{3, 4, 5},
{2, 3, 5, 6, 7},
{112, 3}
};
for (int row = 0; row < multi.length; row++) {
for (int col = 0; col < multi[row].length; col++) {
System.out.print(multi[row][col] + " ");

Answer Source

You are almost there, adapt the for loops, dont forget every row is an array as well.....

    String[][] words = new String[2][3];
    words[0][0] = "a";
    words[0][1] = "b";
    words[0][2] = "c";
    words[1][0] = "d";
    words[1][1] = "e";
    words[1][2] = "f";
    for (int row = 0; row < words.length; row++) {
        for (int col = 0; col < words[row].length; col++) {
            System.out.println(words[row][col]);
        }
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download