munchschair
munchschair

Reputation: 1683

Can I use an enhanced for loop to print two dimensional arrays?

I am learning about these things and I am used to using regular iterator for loops. Anyway, I was wondering if I could print this simple array:

    public class enchancedtwodimdemo
{
    public static void main (String[] args)
    {
        String[][] chords = {{"A", "C", "D", "E"},{"Am","Dm"}};
    }    

}

Upvotes: 2

Views: 6514

Answers (5)

Sri venkat Chennu
Sri venkat Chennu

Reputation: 1

Yes, we can definetly do so using enhanced for loop.

int arr[][] = { { 1, 2, 3 },
                     { 4, 5, 6 },
                     { 7, 8, 9 } };

for(int[] i:arr){

    for(int a:i){

        System.out.print(a);


    }

    System.out.println();

}

Upvotes: 0

Leo Jr Obispado
Leo Jr Obispado

Reputation: 1

Muti-Dimentional Array is an array of array. Try to add this to your code:

    for (String rows[]: chords) {
        for(String cols: rows) {
            System.out.println(cols+"\t");
        }
            System.out.println();
    }

Upvotes: 0

yshavit
yshavit

Reputation: 43391

Sure. You can use one enhanced-for to get at the "inner" String[]s, and then another to print each String within that.

(I presume you meant to write String[][] = {{...}}.)

There's no general way of getting at the leaf elements of a nested structure. But if all you want to do is to print it, you could take a look at Arrays.deepToString, which handles that nested access for you.

Upvotes: 3

Christian Tapia
Christian Tapia

Reputation: 34146

First of all, String[] is a one-dimensional array. A two-dimensional array would be:

String[][] chords = { { "A", "C", "D", "E" }, { "Am", "Dm" } };

and you can use enhanced-for loops to loop first, through 1-D arrays (String[]) and then to loop through each String:

for (String[] array : chords) {
    for (String string : array) {
        // ...
    }
}

Note that when you use an enhanced-for loop, you have to specifiy the type of the elements.

Upvotes: 0

Pradeep Simha
Pradeep Simha

Reputation: 18123

Sure, you can do like this:

for(String[] str:chords) {
   for(String value:str) {
      //Do anything with 'value' here
   }
}

I haven't compiled, but this should work.

Upvotes: 2

Related Questions