Samuel
Samuel

Reputation: 18586

Possible loss of precision / [type] cannot be dereferenced

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!

Upvotes: 2

Views: 876

Answers (2)

polygenelubricants
polygenelubricants

Reputation: 383756

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

Upvotes: 1

ChrisF
ChrisF

Reputation: 137148

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.

Upvotes: 3

Related Questions