views:

68

answers:

2

I have been looking around a lot but i simply can't find a nice solution to this...

Point mouse = MouseInfo.getPointerInfo().getLocation();

int dx = (BULLET_SPEED*Math.abs(x - mouse.getX()))/
                    (Math.abs(y - mouse.getY()) + Math.abs(x - mouse.getX()))*
                    (x - mouse.getX())/Math.abs(x - mouse.getX());

In this constellation i get: Possible loss of precision, when i change e.g (x - mouse.getX()) to (x - mouse.getX()).doubleValue() it says double cannot be dereferenced, when i add intValue() somewhere it says int cannot be dereferenced. What's my mistake?

[x, y are integers | BULLET_SPEED is a static final int]

Thanks!

+1  A: 

Just cast with (int)

int i = (int) 3.14159; // compiles fine

This will not avoid any loss of precision, but it makes explicit to the compiler that it's what you want, so the code would compile.

Do keep in mind where casting sits in the precedence.

int i = (int) .1D + .1D; // doesn't compile!!!
int j = (int) (.1D + .1D); // compiles fine

Related questions


On dereferencing errors

Primitives are not objects; they have no members.

    Integer ii = 42; // autoboxing
    int i = ii.intValue(); // compiles fine
    int j = i.intValue(); // doesn't compile

See also


So in this specific case, you can do the following:

int dx = (int) (BULLET_SPEED*Math.abs(x - mouse.getX()))/
                (Math.abs(y - mouse.getY()) + Math.abs(x - mouse.getX()))*
                (x - mouse.getX())/Math.abs(x - mouse.getX());
polygenelubricants
Where'd i put the (int)?
Samuel
@Samuel: see latest revision.
polygenelubricants
thank you :) works fine (+ i'm gonna read those)
Samuel
+3  A: 

I'd store x, y and BULLET_SPEED as double, perform all the arithmetic in double and then cast to int as a final step.

ChrisF
Yeah i'm considering that, but i'd have to change all parameters of all functions from int to double than, because x and y are widely used
Samuel
Or add double_x and double_y locals to the function and do the arithmetic on those.
pdbartlett