user2173361 - 1 year ago 64
Java Question

# Point x value changes for no reason

I have this method for looking for a free position inside a matrix. This is the output i get when I print the

`matrix`
.

``````1 0 0 0 0 0 0
1 1 1 0 0 0 0
1 1 1 0 0 0 0
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
``````

I have a
`currentPos`
of
`(0,0)`
. The next free Position should be (0,1). when I call
`NextFreePos()`
it will change the
`currentPos.x`
value even though It shouldnt change. I only change the
`x`
if i get a true in the second for loop, but this always returns
`false`
, because I make
`stop = true`
inside the first for loop
Here is the output I get when I run this method:

``````NEXT POS = (0;0)
SAME X
NEXT POS = (1;1) // I dont get why the x (first value) changed to 1

public void nextFreePos(Point currentPos){
// display the OLD POS (x,y) <-- x = row and y = column
System.out.println("OLD POS = ("+(currentPos.x)+";"+currentPos.y+")");
boolean stop = false;
// check if there is a free Pos in current row, starting from current y
for(int y = currentPos.y; y < 7; y++){
// check if Position is free and no free position has been found yet
if(matrix[currentPos.x][y] == 0 && stop == false){
stop = true;
System.out.println("SAME X");
currentPos.y = y;
}
}
currentPos.x++;
for(int x = currentPos.x; x < 7; x++){
for(int y = 0; y < 7; y++){
// check if Position is free and no free position has been found yet
if(matrix[x][y] == 0 && stop == false){
stop = true;
System.out.println("OTHER X");
// set the position to x and y
currentPos.x = x;
currentPos.y = y;
}
}
}
// display the NEXT POS (x,y)
System.out.println("NEXT POS = ("+currentPos.x+";"+currentPos.y+")");
}
``````

See the highlighted piece of code.

``````NEXT POS = (0;0)
SAME X
NEXT POS = (1;1) // I dont get why the x (first value) changed to 1

public void nextFreePos(Point currentPos){
// display the OLD POS (x,y) <-- x = row and y = column
System.out.println("OLD POS = ("+(currentPos.x)+";"+currentPos.y+")");
boolean stop = false;
// check if there is a free Pos in current row, starting from current y
for(int y = currentPos.y; y < 7; y++){
// check if Position is free and no free position has been found yet
if(matrix[currentPos.x][y] == 0 && stop == false){
stop = true;
System.out.println("SAME X");
currentPos.y = y;
}
}
``````
``````        currentPos.x++;
``````
``````        for(int x = currentPos.x; x < 7; x++){
for(int y = 0; y < 7; y++){
// check if Position is free and no free position has been found yet
if(matrix[x][y] == 0 && stop == false){
stop = true;
System.out.println("OTHER X");
// set the position to x and y
currentPos.x = x;
currentPos.y = y;
}
}
}
// display the NEXT POS (x,y)
System.out.println("NEXT POS = ("+currentPos.x+";"+currentPos.y+")");
}
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download