This site requires JavaScript, please enable it in your browser!
Greenfoot back
Fargesia
Fargesia wrote ...

2019/9/10

variable=otherVariable?

Fargesia Fargesia

2019/9/10

#
Hi! I have two two dimensional matrix, and I want one to equal another how do I do it? I mean here's my code:
plateauModif=plateau;
                plateauModif[1][1]=-8;
                plateauModif=plateau;
Here plateauModif should get back to plateau right? But it actually changes the plateau variable to make it equal to plateauModif? Shouldn't it be the contrary? Seems pretty basic but I don't understand why it's reacting like that.
danpost danpost

2019/9/10

#
An array (regardless of number of dimensions) is an object (of type java.util.Array). Your line 1 gives your plateau array a new reference name (an alternate name). It does not make a duplicate array. Any changes done using either name applies to your one, and only, array. Line 3 does nothing as both references already point to the same array. Object variable names are basically a special type of number field which stores a memory location where some object description begins (a pointer value). So, your line 1 basically sets plateauModif to point to the same object that plateau points to.
Fargesia Fargesia

2019/9/10

#
Ok many thanks I made it like that to get it working:
for(int j=0; j<=7; j++){
                    for(int k=0; k<=7; k++){
                        plateauModif[j][k]=plateau[j][k];
                    }
                }
Working just fine now, thanks!
You need to login to post a reply.