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

2014/5/17

Actor returning null

dan11 dan11

2014/5/17

#
Hi, I'm trying to set an integer in one class (bl) to equal an integer in another class (or). I have done this many times before, but for some reason it is not working anymore. The class with the original integer (bl) is returning null, even though it has been added to the world. Code for or:
 
    public int xx;
    public int yy;
    public int rr;
    int x = 0;
    int y = 0;
    public bl b;
    int o = 0;
    public void addedToWorld(World tron){
        setRotation(180);
    }
    /**
     * Act - do whatever the or wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {   
        
        tron t = (tron)getWorld();
        b = t.getBl();
        if(b!=null){  //b is returning null, if I got rid of this line I would get nullPointerException  
            xx = b.x();
            yy = b.y();
            rr = b.r();
        }
Code for the world class tron:
import greenfoot.*; 

/**
 * Write a description of class tron here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class tron extends World
{
    private bl bl_;
    private or o;
    public int x = 0;
    public int y = 0;
    public int r = 0;
    /**
     * Constructor for objects of class tron.
     * 
     */
    public tron()
    {            
        super(800, 600, 1); 
        bl bl_ = new bl();
        addObject(bl_,200,300);
        or o_ = new or();
        addObject(o_,600,300);
    }

    public void act(){
        int c = 0;

        prepare();
        c = 7;

    }
    public bl getBl()
    {
        return bl_;
    }

    public void prepare(){

    }
    
}
davmac davmac

2014/5/17

#
First: by convention, classes in Java should start with a capital letter; 'bl' should be 'Bl' (or even 'BL') and so on. It's hard for more experienced Java programmers to understand your code if you don't use this convention! Second: the problem is that you are shadowing the instance variable, on line 23:
        bl bl_ = new bl();  
This is a full variable declaration (with type) so it creates a new variable (which is local to the method, and which ceases to exist once the method returns). You actually just wanted to set the value of the existing variable, which should be written as:
        bl_ = new bl();
dan11 dan11

2014/5/17

#
Thank you very much, I even did it right in my other scenarios, don't know why I did that here.
You need to login to post a reply.