devdoe
devdoe

Reputation: 4325

for each loop inside foreach loop?

This gives error. Any other method to extract elements from a multi dimensional array one by one ?

I thought that for a foreach loop(variable holding corresponding value : array/Iterable), it is possible to first get the one dimensional array from a multiD. array and then create another foreach loop that extract elements from that array. But it gives all sorts of errors in foreach loop.

1st error: Array2D.java:14: error: not a statement for(a : arr[] )

Code Behind:

class Array2D {
    public static void main(String[] args) {
        int[][] array = new int[][]
        {
                { 1, 2, 3 },
                { 4, 5, 6 },
                { 7, 8, 9 }
        };

        int a[] = new int[3];

        for(a : array) {
            for(int n : a) {
                System.out.print(n + " ");
            }
        }
    }
}

Upvotes: 1

Views: 2250

Answers (4)

Hovo
Hovo

Reputation: 190

C# supports the following arrays:

  1. single-dimensional arrays
  2. multidimensional arrays (also called rectangular arrays)
  3. array-of-arrays (also called jagged arrays).

Examples:

int[] numbers; // Single-dimensional arrays // 1

string[,] names; // Multidimensional arrays // 2

int[][] detail;  // jagged arrays // 3

It is worthy to note that in C# arrays are objects and must be instantiated.

So, instantiation for the above samples might look like:

int[] numbers = new int[5];  // 1

string[,] names = new string[5,4]; // 2

int[][] detail = new int[7][];    // 3
for (int d = 0; d < detail.Length; d++)
{
  detail[d] = new int[10];
}

As to your sample, it might be rewritten to the following way:

static void Main(string[] args)
{
    int[][] arr = new int [][]
    {
        new int[] {1,2,3},
        new int[] {4,5,6},
        new int[] {7,8,9}
    };

    for (int i = 0; i < arr.Length; i++)
    {
        for (int j = 0; j < arr[i].Length; j++)
        {
            System.Console.Write(arr[i][j] + " ");
        }
        System.Console.WriteLine();
    }
}

With Java, I think it will look like

for(int[] arr : array)
{
    for(int n : arr)
    {
        System.out.print(n + " ");
    }
}

Upvotes: 2

Keppil
Keppil

Reputation: 46209

You need to change the first for statement. Also, you must move the int[] a declaration:

for(int[] a : arr) {
    ...
}

Upvotes: 2

Brian Agnew
Brian Agnew

Reputation: 272217

I would try:

for (int r = 0; r < arr.length; r++) {
   for (int c = 0; c < arr[r].length; c++) {
      // c and r are the indexes into the array
   }
}

which gives you the indexes of the array element by iterating across the length of each array/array row.

Or if you just need the elements without the indexes

   for (int[] a : arr) {
      for (int b : a) {
         // gives you the element in b
      }
   }

Upvotes: 1

Random42
Random42

Reputation: 9159

In the first for put:

for(a : arr) {
//
}

Upvotes: -1

Related Questions