letsgo00 letsgo00 - 1 year ago 115
Java Question

How to get the difference between two integers

I'm trying to make a program which uses areas and each area has an id (e.g.:1;1) and I'm trying to get the size of a specified area with comparing two ids but this method returns 1 as size.

//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);

So how can I make this work?

Answer Source

The result is 1 because compareTo() returns 0 if the arguments are equal, -1 if the first int is smaller than the second one and 1 if the second one is smaller (you can read more about it in the official docs).

--> You should not use this method for this purpose. Calculate the difference instead:

int x = pos2.x - pos1.x;
int y = pos2.y - pos1.y
int size = Math.abs(x * y);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download