| Author |
Enhanced for Loop(for Arrays)
|
asha ganapathy
Ranch Hand
Joined: Nov 03, 2006
Posts: 54
|
|
I wrote this piece of code to print the values of a two dimensional array (after i reffered from K&B book page no.339) class test{ public static void main(String[] args){ int [][] a = {{1,2,3},{4,5,6},{7,8,9}}; for(int[] n : a) System.out.println(n); } } But the result i get are not the elements of the array, it looks like [I@187c6c7 Can anyone explain why am i getting these kind of errors?
|
 |
camilo lopes
Ranch Hand
Joined: Aug 08, 2007
Posts: 202
|
|
|
you have a bidimensional Array, or either, an Array inside of another Array, entao it prints the value of the object and nao the elements.
|
Brazil - Sun Certified Java Programmer - SCJP 5
http://www.camilolopes.com/ About Java - Update every Week.
Guide SCJP - tips that you need know http://blog.camilolopes.com.br/livrosrevistaspalestras/
|
 |
asha ganapathy
Ranch Hand
Joined: Nov 03, 2006
Posts: 54
|
|
But in the book it says int [][] twoDee ={{1,2,3},{3,4,5},{5,6,7}}; for(int[] n :twoDee);//loop thru the array of arrays now how do i print the elements of the array twoDee?
|
 |
camilo lopes
Ranch Hand
Joined: Aug 08, 2007
Posts: 202
|
|
if you to want yes.
|
 |
John Bartlett
Ranch Hand
Joined: Jan 25, 2006
Posts: 116
|
|
Hi, If you want to print out the entries of - int [][] twoDee ={{1,2,3},{3,4,5},{5,6,7}}; you would have to do this; John
|
 |
asha ganapathy
Ranch Hand
Joined: Nov 03, 2006
Posts: 54
|
|
oh ok i got it.. thanks a lot, so if i have to print the full array then i can say System.out.println(n[0]+" "+n[1]+" "+n[2]);
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
Originally posted by asha ganapathy: ...the result i get are not the elements of the array, it looks like [I@187c6c7...
Actually, you are getting the elements of the array. Remember, in Java, multi-dimensional arrays are really just arrays that contain other arrays. When you say for(int[] n : a), this means for each int array (referenced by n) that is an element of the array a. So when you print n, you get a String representation of the array itself (which is an object) -- not the contents of that array. (In this case, the String representation uses the left bracket "[" to indicate an array, "I" to indicate the type of array as int, followed by a memory address.) If you want to print the contents of this array (n), you will need to iterate through the elements of n. And since this is a multi-dimensional array (arrays within arrays), that's where nested loops come in. In psuedo code (lacking the iteration details)...
|
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
|
 |
 |
|
|
subject: Enhanced for Loop(for Arrays)
|
|
|