Java - If statement A is equal to B plus or minus 2

if-statement, java

Solution

You can use `Math.abs`:

if (Math.abs(float_a-float_b) <= 2) { ... }

This means "if the absolute difference between a and b is within 2...".

Problem

I've got a problem that seems easy to solve, however I'm not sure on the syntax. I need to have an if/else statement run, but I'm not sure on how to set the conditions correctly. Bad code: ``` if (float_a = float_b or is within +-2 of it) { do this } else { do that } ``` What's the simplest way of accomplishing this?

Original source