For Java, you can use a Predicate<Double>
. That would be the simplest way.
By the way, I am assuming that your intervals do not overlap. If they do, provide clarification via an edit to your post, and then comment on my answer, notifying me.
public enum Behavior
{
SMILE(4),
FUNNY(3),
NORMAL(2),
SAD(1),
CRY(0),
;
final int behaviorCode;
private final java.util.function.Predicate<Double> range;
Behavior(final int behaviorCode)
{
this.behaviorCode = behaviorCode;
this.range = x -> this.behaviorCode < x && x <= this.behaviorCode + 1;
}
public static Behavior forValue(final double value)
{
for (final Behavior each : Behavior.values())
{
if (each.range.test(value))
{
return each;
}
}
throw new IllegalArgumentException("value does not match any of the Behaviour Codes! value = " + value);
}
}
If I run it, here is how it goes.
Behavior.forValue(5) ---> Behavior.SMILE
Behavior.forValue(4.9999) ---> Behavior.SMILE
Behavior.forValue(4.0001) ---> Behavior.SMILE
Behavior.forValue(4) ---> Behavior.FUNNY
Behavior.forValue(4.0) ---> Behavior.FUNNY
Behavior.forValue(3.9999) ---> Behavior.FUNNY
Behavior.forValue(3) ---> Behavior.NORMAL
Behavior.forValue(2) ---> Behavior.SAD
Behavior.forValue(1) ---> Behavior.CRY
Behavior.forValue(0) ---> java.lang.IllegalArgumentException: value does not match any of the Behaviour Codes! value = 0.0
Behavior.forValue(5.0001) ---> java.lang.IllegalArgumentException: value does not match any of the Behaviour Codes! value = 5.0001
Behavior.forValue(6) ---> java.lang.IllegalArgumentException: value does not match any of the Behaviour Codes! value = 6.0
Behavior.forValue(42) ---> java.lang.IllegalArgumentException: value does not match any of the Behaviour Codes! value = 42.0