| Author |
How to create multidimension array using for each loop?
|
awad saleh
Greenhorn
Joined: Jul 04, 2007
Posts: 22
|
|
Hi i have created multidimension array and accessed the values using for loop? how can we do using for-each loop? class MultiArray { int arr[][]; public MultiArray() { arr = new int[][]{{1,2,3},{4,5,6,7},{8,9,10,11,12}}; } public void forLoop() { for(int i=0;i<arr.length;i++) { for(int j=0;j<arr[i].length;j++) { System.out.print(arr[i][j]+" "); } System.out.println(); } } public static void main(String[] args) { MultiArray ma = new MultiArray(); ma.forLoop(); } }
|
 |
Arthur Buliva
Ranch Hand
Joined: Mar 08, 2006
Posts: 101
|
|
|
Your question is not clear. What do you need? Please rephrase!
|
 |
Peter Chase
Ranch Hand
Joined: Oct 30, 2001
Posts: 1970
|
|
Yet another copy of this same message. Don't cross-post! Bartender will probably kill this thread.
|
Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.<br /> <br />#:^P
|
 |
asha ganapathy
Ranch Hand
Joined: Nov 03, 2006
Posts: 54
|
|
class MyClass { int arr[][]; public MyClass() { arr = new int[][]{{1,2,3},{4,5,6,7},{8,9,10,11,12}}; } public void forLoop() { for(int i: arr[0]) { System.out.print(i); } for(int j:arr[1]) { System.out.println(j); } for(int k:arr[2]) { System.out.println(k); } } public static void main(String[] args) { MyClass ma = new MyClass(); ma.forLoop(); } } I think this is one of the ways to print the multidimensional array using for-each loop
|
 |
asha ganapathy
Ranch Hand
Joined: Nov 03, 2006
Posts: 54
|
|
But if your array had equal no of rows and cols then you could try this. public class MyClass { public static void main(String args[]) { int[][] a = { {1,2,3} , {4,5,6} , {10,11,12} }; for(int[] i : a) { System.out.println(i[0]+" "+i[1]+" "+i[2]); } } }
|
 |
gaurav abbi
Ranch Hand
Joined: Jan 05, 2007
Posts: 108
|
|
there are also some new APIs added in Arrays class for doing such operation have a look at those.
|
thanks,<br />gaurav abbi
|
 |
 |
|
|
subject: How to create multidimension array using for each loop?
|
|
|