Search code examples
javadoublegreenfootvariable-types

Force Java to use double instead of int


I have the following code:

public void keyboard() {
    int sealX;
    double sealY;
    if (Greenfoot.isKeyDown("up")) {
        sealX = getX();
        sealY = getY();
        setLocation(sealX, (sealY - 1.25));
    }
    if (Greenfoot.isKeyDown("down")) {
        sealX = getX();
        sealY = getY();
        setLocation(sealX, (sealY + 1.25));
    }
}

Initially, the variable sealY was an integer, like sealX. However, 1 ended up being too small as an incremented in the two conditionals below, and 2 was too large.

The program compiled and worked fine before. But as soon as I changed sealY to a double and changed the operation that are done on keyboard input to numbers with decimals (doubles), Java started throwing the error - Incompatible types: possible lossy conversion from double to int

I've seen this before at times where I was using a double unnecessarily and an integer would have sufficed. However, that is not the case here. An integer will not suffice. I find that this isn't a fatal error and is more of a tip, but my program won't compile because of that.

Personally, I think the compiler can try to be helpful, but otherwise it's none of its business whether I use a double or an int. There should be a way to override the compiler if I insist upon using a double, particularly because I can't use an integer for what I am trying to do here.

I don't think casting will fix this problem. Is there a way to manually override compilers and declare that I know what I'm doing and I want sealY to be a double?

EDIT: enter image description here

And some documentation:

setLocation public void setLocation(int x, int y) Assign a new location for this actor. This moves the actor to the specified location. The location is specified as the coordinates of a cell in the world. If this method is overridden it is important to call this method as "super.setLocation(x,y)" from the overriding method, to avoid infinite recursion. Parameters: x - Location index on the x-axis y - Location index on the y-axis See Also: move(int)


Solution

  • Casting won't solve your problem as well You have to use :

    sealY = getY().doubleValue();
    

    if getY() returns an int you should use :

    sealY = new Integer(getY()).doubleValue();
    

    EDIT :

    it seems that your setLocation function looks like setLocation(int x, int y);

    so to avoid this error you can only do :

    setLocation(sealX, new Double(y + 1.25).intValue());
    

    or as Radiodef said

    setLocation(sealX, (int) (y + 1.25));
    

    It looks like a dirty trick, but I don't know about any other solution