Sumit Kumar
Sumit Kumar

Reputation: 781

My multiDimentional Array code is not working correctly

My code below gives me unexpected output. What I'm trying to do is create a multi dimentional array, and then populate it with values of x, y, z inside a loop. But for some reason, it fills only the "maximum" value of x, y, z in all elements. Instead it should fill the current value. If you uncomment the first System.out line, you'll see the result I actually want.

public class Test{

public static void main( String args[] ){


int[][] a= new int[ 150 ][3];

int[] val = new int[3];
int increment =0;

for( int x=0; x<10; ++x ){
for( int y=0; y<5; ++y ){
for( int z=0; z<3; ++z ){

val[0]=x; val[1]=y; val[2]=z;

a[ increment ]=val; 
++increment;
//System.out.println( x+" "+y+" "+z+" "+ increment )

} } }// for

for( int s=0; s<increment; ++s ){ System.out.println( a[ s ][0]+" "+ a[ s ][1]+" "+ a[ s ][2]+" "+ s ); }


}//main
}//class

my output:

9 4 4 0
9 4 4 1
9 4 4 increment

expected output:

0 0 0 0
0 0 1 1
0 0 2 2
...
0 1 1 3
0 1 2 4
    .
    .
    .
upto so on

What did I do wrong?

Upvotes: 2

Views: 49

Answers (1)

dryairship
dryairship

Reputation: 6077

You set the values in val, but then you set a reference of val in each cell of a. Thus, when the value of val is changed, the values all the references change, and hence they all become 9,4,4. the last value is s which keeps on incrementing in your loop. Thus you get that output.

To get the required output, just reset val before each iteration. Add this line:

val = new int[3];

as the first line in your innermost for loop.

Upvotes: 1

Related Questions