Hoping for something more elegant than
if (i>0 && i<100)
Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
if(timeRange.contains(systemtime)){
Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
}
That's how you check is an integer is in a range. Greater than the lower bound, less than the upper bound. Trying to be clever with subtraction will likely not do what you want.
I don't see how that's not elegant, but if you repeat the expression often, then it's a good idea to put it into a method, e.g.
class MathUtil
{
public static boolean betweenExclusive(int x, int min, int max)
{
return x>min && x<max;
}
}
This is particularly true if you mix exclusive and inclusive comparisons. The method name can help avoid typos, such as using < when <= should have been used. The method can also take care of ensuring that min < max etc..
Use this code :
if (lowerBound <= val && val < upperBound)
or
if (lowerBound <= val && val <= upperBound)
This guy made a nice Range class.
Its use however will not yield nice code as it's a generic class. You'd have to type something like:
if (new Range<Integer>(0, 100).contains(i))
or (somewhat better if you implement first):
class IntRange extends Range<Integer>
....
if (new IntRange(0,100).contains(i))
Semantically both are IMHO nicer than what Java offers by default, but the memory overhead, performance degradation and more typing overall are hadly worth it. Personally, I like mdma's approach better.
For those using commons lang an option is to use Range:
Range<Integer> myRange = Range.between(100, 500);
if (myRange.contains(200)){
// do something
}
Also see: how to construct a apache commons 3.1 Range<Integer> object