This site requires JavaScript, please enable it in your browser!
Greenfoot back
VladislavMoldovan
VladislavMoldovan wrote ...

2018/4/7

Converting types

VladislavMoldovan VladislavMoldovan

2018/4/7

#
Why I get an error in this code?
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Car here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Car extends Actor
{
    /**
     * Translates and rotates object due to condition.
     */
    public void act() 
    {
        int pressedA = (int)Greenfoot.isKeyDown("a");
        int pressedB = (int)Greenfoot.isKeyDown("b");
        moveOn(pressedA * (-5) + pressedB * 2);
        turn(pressedA * 2 + pressedB * 5);
    }
    
    /**
     * Translates object on value passed in parameter.
     */
    public void moveOn(int x)
    {
        setLocation(getX() + x, getY());
    }
}
danpost danpost

2018/4/7

#
The isKeyDown method returns a boolean (true/false) value which cannot be converted to an int value. This appears to be what you are trying to do in lines 10 and 11. You can declare the int variables prior to the isKeyDown checks and increment them when the boolean value returned is true:
int pressedA = 0;
int pressedB = 0;
if (Greenfoot.isKeyDown("a")) pressedA++;
if (Greenfoot.isKeyDown("b")) pressedB++;
moveOn(pressedB*2-pressedA*5);
turn(pressedA*2+pressedB*5)
You need to login to post a reply.