检查范围内的int [英] Checking an int within range

查看:176
本文介绍了检查范围内的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; 
}

这篇关于检查范围内的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆