I'm getting a compilation error in the following code, saying that operators can't be used for the boolean or double.
I want to return a boolean that indicates if x
is in that range or not.
public static Boolean estaEnIntervalo (double x){
return (-5.0<=x<=2.0 || 0.0<x<=1.0 || 2.0<=x<5.0);
}
You cannot combine relational operators this way, as you would in math. How Java interprets -5.0<=x<=2.0
:
-5.0<=x
produces a boolean
, but boolean<=2.0
doesn't make sense.
You must create separate expressions for each bound.
return ((-5.0<=x && x<=2.0) || (0.0<x && x<=1.0) || (2.0<=x && x<5.0));
-5.0<=x<=2.0 is not a valid expression. You need to use (-5.0 <= x) && (x <= 2.0), and similarly for the other checks too.
Also remember that Boolean is not the same as boolean. One is an object, and one is a primitive. As pointed out by SamTebbs33.
You have to split each range into two conditions conbined with AND :
return ((-5.0<=x && x<=2.0) || (0.0<x&&x<=1.0) || (2.0<=x&&x<5.0));
Now, your condition checks if x if within any of three ranges :
[-------------------------------]
(----] [------------]
-5 0 1 2 5
Since these ranges overlap, so you can simply have a single range condition :
return (-5.0<=x && x<=5.0);
The following is an invalid boolean expression (-5.0 <= x <= 2.0)
It must be changed to (x <= 2.0 && x >= -5.0)
In addition, you have to return a Boolean
object.
return new Boolean((x <= 2.0 && x >= -5.0) || (x <= 1.0 && x > 0.0) || (x < 5.0 && x >= 2.0));
Otherwise, rearrange the expression like I did and change the return type to boolean
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.