...

View Full Version : Way to print a 2D array.



sunzeal
03-01-2012, 05:27 PM
Hi

This is a simple way for writing a 2D array :-

int twoD[][]={{0,1,2,3,4},{5,6,7,8,9}};

But problem is how can i print it ?

I tried system.out.println(twoD [] [] ), but it gave error :(

Any help, i want to print the whole array.

Fou-Lu
03-01-2012, 06:25 PM
If you mean to print out the array id, then you can simply use System.out.println(twoD);. If you intend to actually show what is in them, use a collection or write a loop / recursive method to display the items within the array.

sunzeal
03-02-2012, 12:21 AM
If you mean to print out the array id, then you can simply use System.out.println(twoD);. If you intend to actually show what is in them, use a collection or write a loop / recursive method to display the items within the array.

i tried printing (twoD) and the output was : "[[I@19821f " << can you please tell me how ?

also can you please mention the loop ? actually we have this program in our exams and its really frustrating at the method our sir taught us so wanna go for simpler one.

Fou-Lu
03-02-2012, 12:25 AM
As I said, the output of a print is that of the memory identifier.
And what method were you shown? I'm willing to bet its either a collection conversion or that of looping as is. Printing takes either the use of a primitive scalar, or a .toString() on an object. Since an array of primitive is a complex type, you cannot just print it directly.

sunzeal
03-02-2012, 12:33 AM
As I said, the output of a print is that of the memory identifier.
And what method were you shown? I'm willing to bet its either a collection conversion or that of looping as is. Printing takes either the use of a primitive scalar, or a .toString() on an object. Since an array of primitive is a complex type, you cannot just print it directly.

we had to print 2D array program such as :-

0 1 2 3 4
5 6 7 8 9
10 11 13 13 14
15 16 17 18 19

so its like 4 rows and 5 colums, their were total 4 for loops in program, the first 2 were to assign values ( 0 - 19 ) with help of variable, and other 2 for loop was used to print the variables.

Fou-Lu
03-02-2012, 12:58 AM
Assignment is irrelevant since you need to populate them somehow.
2 loops for a 2d array is what you need to do. Each level is another loop. Recursion is the other option since then you don't need to concern yourself with the depth.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum