java - 如何获得两个整数之间的差

标签 java math compare

我正在尝试制作一个使用区域的程序,每个区域都有一个 ID(例如:1;1),我正在尝试通过比较两个 ID 来获取指定区域的大小,但此方法返回 1 作为尺寸。

 //Pos1 = -2;3 Pos2 = 0;1
 int x = Integer.valueOf(pos2.x).compareTo(pos1.x);
 int y = Integer.valueOf(pos2.y).compareTo(pos1.y);
 int size = Math.abs(x * y);

那么我怎样才能让它发挥作用呢?

最佳答案

compareTo 不应该返回两个值之间的确切差异。来自 the docs :

Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

使用

int x = Math.abs(pos2.x-pos1.x);
int y = Math.abs(pos2.y-pos1.y);
int size = x * y;

关于java - 如何获得两个整数之间的差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38078503/

相关文章:

Java:ChaCha20 w/Poly1305 作为通用文件加密的 MAC

iphone - 射线-三角形交叉点拾取不起作用

javascript - 围绕一条线创建一个多边形

algorithm - 分而治之矩阵乘法

c++ - 如何比较类中的两个对象(调用对象和参数)?

c# - 在 C# 中比较字符串

java - JButton ActionListener 两人游戏

java - 涉及标识符 R 的错误(将一个项目嵌入另一个项目时)

java - PriorityQueue 的 remove 方法是否重新排列堆?

java - Guava Resources getResource() 第一次不工作