简体   繁体   中英

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"}};
    }    

}

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 .

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM