Java chained inequality if (5<i<10)

那年仲夏 提交于 2021-02-03 11:27:57

问题


Is there any operator or trick for such operation? Or is it necessary to use

if(5<i && i<10)

?


回答1:


There is no such thing in Java (unless you work with booleans).

The 5<iresults in a boolean on the left side on <10 which the compiler dislikes.




回答2:


You cannot chain inequalities. You can, however, define a static boolean method isInRange(value, low, high) that will perform such a check.

Some other languages, like Python or Icon, allow this notation.




回答3:


You can use a single comparison but is more complicated than its worth usually.

if (i - (Integer.MIN_VALUE + 6) < Integer.MIN_VALUE + (10 - 6))

This uses underflow to adjust all the value 5 and below to be a large positive value.

The only reason you would use this is as a micro-optimisation.




回答4:


I'm afraid chained inequalities are unsupported in Java at this time. Check this post for languages which do.




回答5:


Range

Comparisons cannot be chained in Java.

The standard way for doing a range check is to use either Guava Ranges:

import com.google.common.collect.Range;
...
    if(Range.open(5, 10).contains(x)){

or Apache Commons Lang (it provides only closed ranges, though):

import org.apache.commons.lang3.Range;
...
    if(Range.between(5 + 1, 10 - 1).contains(x)){



回答6:


a < x < b is equivalent to (x-a)(x-b)<0, or if x is an expression you only wanna calculate once,

(x - (a+b)/2) ^ 2 < (b-a)^2 / 4

Same deal with two nonstrict equalities. I don't think there's a way to deal with one strict and one nonstrict equality, however (unless x is an integer).



来源:https://stackoverflow.com/questions/10658343/java-chained-inequality-if-5i10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!