检查整数的最简单方法是+1或-1 Java

时间:2014-02-20 17:44:37

标签: java loops integer comparison

我想两个整数之间的区别是+1或-1。我认为下面的代码写得非常笨拙。有没有更短的方法来检查两个整数是否只是1?这似乎是一个简单的解决方案,但我有2d坐标数组我想检查是否选择了彼此的直接附近(北,东,西或南)的两个坐标。 < / p>

是的,它们是标准坐标,因为左上角是0,0,右下角是7,7。基本上如果选择了一个坐标,我想检查是否存在另一个坐标,其中x或y相差(+ - )一个。

//Since it's a 2d array, I am doing a nested loop. But comparison is below

int x1 = range(0,8); //all ints are range from 0 to 7
int y1 = range(0,8); //represent the current indices from the loop

int x2 = ...; //x2 represents the x index value of the previous loop
int y2 = ...; //y2 represents the y index value of the previous loop

if(x1+1 == x2){
    Found an existing X coord just larger by one
}else if (x1-1 == x2){
    Found an existing X coord smaller, and differ by one
}else if(y1+1 == y2){
    Found an existing Y coord just 1 larger
}else if(y-1 == y2){
    Found an existing Y coord just 1 smaller
}

4 个答案:

答案 0 :(得分:1)

我能想到的最简单的方法是:

boolean differenceOfOne = Math.abs(n1 - n2) == 1;

n1n2是数字。

答案 1 :(得分:1)

怎么样:

   Math.abs(difference)==1

答案 2 :(得分:1)

您可以使用Math.abs来评估差异:

boolean isDifferenceOne = Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1

答案 3 :(得分:1)

由于我们不关心x1和x2之间的差异是1还是-1,我们可以使用绝对值:

if (Math.abs(x1 - x2) == 1){
    // x coordinates differ by 1
} else if (Math.abs(y1 - y2) == 1){
    // y coordinates differ by 1
}

这是有效的,因为如果x1小于x2,那么Math.abs(x1 - x2) = Math.abs(-1) = 1