检查范围内的int
在java中是否有一种优雅的方法来检查int是否等于或大于/小于1的值。
Is there an elegant way in java to check if an int is equal to, or 1 larger/smaller than a value.
例如,如果我检查 x 大约 5
。我想在 4,5和6
上返回true,因为4和6距离5只有一个。
For example, if I check x
to be around 5
. I want to return true on 4, 5 and 6
, because 4 and 6 are just one away from 5.
是否有功能构建这样做?或者我最好这样写它?
Is there a build in function to do this? Or am I better off writing it like this?
int i = 5;
int j = 5;
if(i == j || i == j-1 || i == j+1)
{
//pass
}
//or
if(i >= j-1 && i <= j+1)
{
//also works
}
当然上面的代码很丑陋且难以阅读。那么还有更好的方法吗?
Of course the above code is ugly and hard to read. So is there a better way?
用 Math.abs找出它们之间的绝对差异
private boolean close(int i, int j, int closeness){
return Math.abs(i-j) <= closeness;
}
根据@GregS关于溢出的评论,如果你给 Math.abs
一个不符合整数的差异你会得到一个溢出值
Based on @GregS comment about overflowing if you give Math.abs
a difference that will not fit into an integer you will get an overflow value
Math.abs(Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 1
通过转换其中一个参数到一个很长的 Math.abs
将返回一个很长的含义,即差异将正确返回
By casting one of the arguments to a long Math.abs
will return a long meaning that the difference will be returned correctly
Math.abs((long) Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 4294967295
因此,考虑到这一点,该方法现在将如下所示:
So with this in mind the method will now look like:
private boolean close(int i, int j, long closeness){
return Math.abs((long)i-j) <= closeness;
}