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?
if we are told to find the difference between 3 and 5, then we usually subtract 3 from 5 ,5-3=2 and thus, we say that the difference is 2.
Subtraction of integers can be written as the addition of the opposite number. To subtract two integers, rewrite the subtraction expression as the first number plus the opposite of the second number. Some examples are shown below. To subtract two integers, add the opposite of the second integer to the first integer.
compareTo
is not supposed to return the exact difference between two values. From 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.
Use
int x = Math.abs(pos2.x-pos1.x);
int y = Math.abs(pos2.y-pos1.y);
int size = x * y;
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With