'How to use greater than and less than in a single if statement in Java
I made a BMI calculator. One of the things I have to do is add categories using if statements. 18.5 to 24.9 normal weight so that would be one of the categories.
This is the way I have tried to do it.
else if ( (bmi >18.5) && (<24.9))
Obviously this won't work for me, what way should I write this I feel like there is a way to write 18.5 to 24.9 instead of using greater than or equal to but I honestly don't even know what to look up.
Link to code http://pastebin.com/gNE7VwE1
Solution 1:[1]
Use
if ( bmi > 18.5 && bmi < 24.9)
Unfortunately, Java does not support a 'BETWEEN' operator (like what SQL does e.g).
Solution 2:[2]
You could write your own method to check if between,
public static boolean isBetween(int low, int high, int bmi) {
return high > low ? bmi > low && bmi < high : bmi > high && bmi < low;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Laurel |