Win a copy of Spring in Action (5th edition) this week in the Spring forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

How to create multidimension array using for each loop?  RSS feed

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
}
}
 
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your question is not clear. What do you need? Please rephrase!
 
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yet another copy of this same message. Don't cross-post!

Bartender will probably kill this thread.
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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]);
}
}
}
 
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
there are also some new APIs added in Arrays class for doing such operation
have a look at those.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!