aspose file tools*
The moose likes Beginning Java and the fly likes enhanced for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "enhanced for " Watch "enhanced for " New topic
Author

enhanced for

venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
why cant we use enhanced for loop for two dimensional variables??? please explain


SCJP1.5
venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
Oops.. am sorry, i meant,

why cant i get the output for this program where i have used two dimen array,
my output was,
[I@3e25a5
[I@19821f
(which made me think that i cant use 2d here..)
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

The issue isn't so much with the enhanced for loop; its the System.out.println() call with an array as the parameter. This is resulting in an implicit call to the toString() method on an array. As such, you do not get the contents of the array output. Even if you do this outside of a for loop, you'd get something similar. For example, the code:


would output something like:
[I@9304b1


To print out the contents of the array, we need to use a utility method in the java.util.Arrays class (notice the plural Arrays). In particular, we can use one of the overloaded toString() methods:



This would result in the output:
[1, 2, 3]


So you can change your code to

And that will output the each of the arrays. So you'd get:

[5, 3, 2]
[4, 3, 2]


And if you want to iterate through the "sub-array" you can out a seconffor loop inside the first for loop:

This would output:

5
3
2
4
3
2

Does that help?
[ August 15, 2008: Message edited by: Mark Vedder ]
venkatesh badrinathan
Ranch Hand

Joined: Aug 03, 2008
Posts: 77
yeah.. really it does.
Thank Mark
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: enhanced for