lordsampigans
lordsampigans

Reputation: 55

Getting error: possible lossy conversion from double to int.... But I'm not using any doubles?

I've done quite a bit of researching, and I'm sure this is just something silly, so I apologize in advance. I'm attempting the CodinGame challenge and I'm using this batch of code.

class Player {

public static void main(String args[]) {
    Scanner in = new Scanner(System.in);

    // game loop
    while (true) {
        int x = in.nextInt();
        int y = in.nextInt();
        int nextCheckpointX = in.nextInt(); // x position of the next check point
        int nextCheckpointY = in.nextInt(); // y position of the next check point
        int nextCheckpointDist = in.nextInt(); // distance to the next checkpoint
        int nextCheckpointAngle = in.nextInt(); // angle between your pod orientation and the direction of the next checkpoint
        int opponentX = in.nextInt();
        int opponentY = in.nextInt();
        int distX = Math.abs(x - nextCheckpointX);
        int distY = Math.abs(y - nextCheckpointY);
        int distance = Math.sqrt(distX * distX + distY * distY);

It goes on a little bit further, but the last line there is where I'm getting my issue. I've commented out the rest of my code to ensure that this is where the error is occurring.

Now, I'm aware that if I take the square root of an int, it's possible for me to get a double, but if I set up the variable as an int, then it should just store as an int... Right? I've even tried to store it as a double or float (which I don't want that anyways) but it still gives me this error. What am I doing wrong?

Upvotes: 1

Views: 243

Answers (1)

Kayaman
Kayaman

Reputation: 73528

Math.sqrt() returns a double, so you need to cast the result to (int) explicitly, to tell the compiler that you understand that there may be information lost. After all, if the result is 2.125, you'll end up with 2 in your int variable. The compiler is just making sure that you understand that, instead of silently dropping off the decimal part.

Therefore add the explicit cast with

int distance = (int) Math.sqrt(distX * distX + distY * distY);

Keep in mind that casting 6.99 to int doesn't round it to 7, it truncates it to 6, which may not be what you want. See Math.round() for rounding the value.

Upvotes: 2

Related Questions