I have the following statement to check if a Vector2D is within a box, and IntelliJ gives me a warning: "if statement can be simplified".

if(point.x < minX || point.x > maxX || point.y < minY || point.y > maxY)
    return false;

How can I simplify this?

有帮助吗?

解决方案

I don't see any possible simplification. I would just ignore the warning.


Update: However, if you method look like this:

if(point.x < minX || point.x > maxX || point.y < minY || point.y > maxY)
    return false;
return true;

You might change it to this:

return !(point.x < minX || point.x > maxX || point.y < minY || point.y > maxY);

Or even:

return point.x >= minX && point.x <= maxX && point.y >= minY && point.y <= maxY;

I don't know if this is "simplified" for humans.

其他提示

Whenever IntelliJ warns of a possible simplification, it often offers to perform the simplification (by clicking the yellow light bulb). What happens if you do that?

Try separating it into two if statements: one for "x" coordinates, one for "y".

if(point.x < minX || maxX < point.x)
    return false;
else if(point.y < minY || maxY < point.y)
    return false;

Maybe you could try something like this:

return new Rectangle(minX, maxX, minY, maxY).contains(point);

As far as simplifying from a boolean algebra perspective, you must be looking for Martin's answer. In fact, you don't even need to simplify it because the compiler will automatically do it for you. For example, !(a && b) will simplify to !a || !b because it is quicker to check each variable separately as opposed to creating a temp variable and check the value of that.

I would just do this.

return !(point.x < minX || point.x > maxX || point.y < minY || point.y > maxY);

and it would remove the warning.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top