How to check if an integer is in a given range?

前端 未结 18 1237
遥遥无期
遥遥无期 2020-11-27 03:58

Hoping for something more elegant than

if (i>0 && i<100) 
相关标签:
18条回答
  • 2020-11-27 04:43
     Range<Long> timeRange = Range.create(model.getFrom(), model.getTo());
        if(timeRange.contains(systemtime)){
            Toast.makeText(context, "green!!", Toast.LENGTH_SHORT).show();
        }
    
    0 讨论(0)
  • 2020-11-27 04:44

    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.

    0 讨论(0)
  • 2020-11-27 04:45

    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..

    0 讨论(0)
  • 2020-11-27 04:45

    Use this code :

    if (lowerBound <= val && val < upperBound)
    or
    if (lowerBound <= val && val <= upperBound)
    
    0 讨论(0)
  • 2020-11-27 04:47

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题