Home > Back-end >  How do I make sure two objects don't have the same coordinates in Java?
How do I make sure two objects don't have the same coordinates in Java?

Time:10-24

I have to write a method that makes sure two objects are not on each other position-wise. The coordinates of these objects have to be randomly generated.

My idea is a while-loop with getX() & getY() methods, that generates new coordinates till the two objects are not on the same spot.

Like this:

int x = getRandom(x);
int y = getRandom(y);
while(object1.getX() == object2.getX() && object1.getY() == object2.getY()){
    int x = getRandom(min, max);
    int y = getRandom(min, max);
}

The code works most of the time. I don't get any error messages, but in the interaction window it can be seen that the rule is not always applied. Does someone maybe have an idea, what I am doing wrong?

CodePudding user response:

Your idea is correct, but you don't have two objects but one object and a pair of int variables. You can use a do-while-loop to shorten the code a bit:

int x, y;
do {
    x = getRandom(min, max);
    y = getRandom(min, max);
} while (x == object.getX() && y == object.getY());

When the loop terminates, point (x,y) is guaranteed to be different from point (object.getX(), object.getY()).

Of course, it would be better to use proper abstractions like e. g. Point to represent a pair of coordinates.

CodePudding user response:

Maybe a problem with the scope of the variables? Try this :

int x = getRandom(x);
int y = getRandom(y);
while((object1.getX() == object2.getX()) && (object1.getY() == object2.getY())){
     x = getRandom(min, max);
     y = getRandom(min, max); 
}
  • Related