Alettix Alettix - 2 months ago 6
Java Question

Method doesn't update variable globally?

So, in the beginning of my java class I define globally:

static long world;
.
Then I have several functions using
world
as an argument. One of theses, called setCell does not work as intended, and I can't figure out why. I have tried error searching with println commands, so now my code looks like this:

public static long setCell(long world, int col, int row, boolean newval){
if(col>= 0 && col<8 && row>=0 && row<8){
int bitPosition = col + 8*row;
long newWorld = PackedLong.set(world, bitPosition, newval);
System.out.println(newWorld);
world = newWorld;
System.out.println(world);
return world;
}
else{
return world;
}
}


The main idea of the code is, that it should update
world
by changing one of its bits with the
PackedLong.set
method (which is working well) and then return the new updated
world
.

If we now run:

world =0x20A0600000000000L;
System.out.println(world);
setCell(world, 1, 1, true);
System.out.println(world);


in the main method, we get the following output:

2350984558603665408
2350984558603665920
2350984558603665920
2350984558603665408


From this I have concluded that the commands inside the
setCell
method works as intended, but that the method does not change
world
"globally" through the whole code. How can I solve this issue?
Many Thanks! :)

Answer

You have the parameter world

public static long setCell(long world, int col, int row, boolean newval)

This will hide the global variable and instead update the parameter. You should avoid names the hide other variables that are present in the same scope. Instead choose a different name for the parameter.

Comments