Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two integers

Tags:

java

math

compare

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?

like image 959
letsgo00 Avatar asked Jun 28 '16 14:06

letsgo00


People also ask

What is the difference between 5 and 3?

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.

How do you subtract integers?

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.


2 Answers

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;
like image 125
f1sh Avatar answered Nov 09 '22 18:11

f1sh


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);
like image 37
Katharina Avatar answered Nov 09 '22 19:11

Katharina