1

Hi Am trying to print 2 dimensional array using for loop. Many places I see nested for loop like

for (..)
  for (..).

But how to print using for loop in declaration and expression . for single dimensional following works

for ( String print_fruit_names : fruit_names )
{
  sysout (names);
};

Am a newbie in java. please let me know if am missing any info to mention.

Yuva Raj
  • 35
  • 1
  • 2
  • 9

1 Answers1

0

You could do it like this with a for each using a Iterator:

String[][] matrix = {{"one", "two", "three"}, {"four", "five", "six"}};

for (String[] sArray: matrix){
  for (String s: sArray){
    System.out.println(s);
  }
}

Or, you could do it like this which just accesses each index directly:

String[][] matrix = {{"one", "two", "three"}, {"four", "five", "six"}};

    for (int i = 0; i < matrix.length; i++){
      for (int j = 0; j < matrix[i].length; j++){
        System.out.println(matrix[i][j]);
      }
    }
Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137