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

2015/1/16

Constructor booleans do not work properly.

Stoeptegel Stoeptegel

2015/1/16

#
Hello! I made different types of trucks. In the constructor parameters are booleans which determine which color it is. This all works fine, when the truck spawns in the desired color it does so. But when i want to access those booleans in the run state (for interaction reasons), it says every boolean is false. Is there any way to fix this?
    public boolean isBlue;
    public boolean isRed;
    public boolean isGrey;
    public boolean isYellow;

    GreenfootImage selectImage;


public Truck (boolean isBlue, boolean isRed, boolean isGrey, boolean isYellow)
    {
        if (isBlue == true)
        {
            selectImage = new GreenfootImage("bluetruck.png");
            setImage(selectImage);
        }
        else if (isRed == true)
        {
            selectImage = new GreenfootImage("redtruck.png");
            setImage(selectImage);
        } 
        else if (isGrey == true) 
        {
            selectImage = new GreenfootImage("greytruck.png");
            setImage(selectImage);
        } 
        else if (isYellow == true)
        {
            selectImage = new GreenfootImage("yellowtruck.png");
            setImage(selectImage);
        }
    }
Super_Hippo Super_Hippo

2015/1/16

#
The booleans which you create in lines 1-4 are initialized as 'false'. You don't set them to 'true' anywhere. In the constructor, you pass booleans which get the same name, but they aren't the same. You could add 'this.isBlue = true;' in the if-block starting in line 11. And so on in the other if-blocks. But it would also be easier if you would use one int.
public int color; //0=blue, 1=red, 2=grey, 3=yellow (of course you can adjust this)
public Truck(int color)
{
    this.color = color;
    switch(color)
    {
        case 0: setImage(new GreenfootImage("bluetruck.png"); break;
        case 1: setImage(new GreenfootImage("redtruck.png"); break;
        case 2: setImage(new GreenfootImage("greytruck.png"); break;
        case 3: setImage(new GreenfootImage("yellowtruck.png"); break;
    }
}
Stoeptegel Stoeptegel

2015/1/17

#
Ah! I almost forgot about switch cases *shame*. Thanks mate! Much improvement :)
You need to login to post a reply.