Search code examples
javamathwhile-looprange-checking

RangeCheck with Positive and Negative Numbers


I'm working on a small game which has a graph. The idea is I do an action whilst the target location (designated by upper and lower bounds) has no been met (within 0.5). For example, if I target (7,7), the loop should stop when x and y are (both in this case) between 6.5 and 7.5.

However, having something such as the following condition has presented me with a problem when presented with negative numbers:

while ((X < tarX-0.5 || X > tarX+0.5) && (Y < tarY-0.5 || Y > tarY+0.5))

For example: if I have the target (-7,-7) then the loop will stop when ONE of the x or y values is in the range, not both.

Basically, I had the idea of having four different loops depending on whether x or y was positive. But I'm wondering if there's an easier way? (I did try to use Math.abs() to counteract the negative numbers, which worked but something destined for (-3,-3) could still then stop at (3,3))


Solution

  • loop should stop when x and y are (both in this case) between 6.5 and 7.5.

    while (!(x >= 6.5 && x <= 7.5 && y >= 6.5 && y <= 7.5)) {
       ...
    }
    

    Applying De Morgan's Law, the above is equivalent to

    while (x < 6.5 || x > 7.5 || y < 6.5 || y > 7.5) {
       ...
    }