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

2020/3/22

showText error

Mattzh Mattzh

2020/3/22

#
I'm getting this error with showText, and I'm not sure why java.lang.NullPointerException at RBC.youLost(RBC.java:79) at RBC.act(RBC.java:29) at greenfoot.core.Simulation.actActor(Simulation.java:567) at greenfoot.core.Simulation.runOneLoop(Simulation.java:530) at greenfoot.core.Simulation.runContent(Simulation.java:193) at greenfoot.core.Simulation.run(Simulation.java:183)
public class RBC extends Actor
{
    private int imageNumber;
    private int newColor;
    public static int rbc = 9;
    public RBC (int i)
    {
        imageNumber = i; //set class image number equal to i
    }
    
    /**
     * Act - do whatever the RBC wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move(1+Greenfoot.getRandomNumber(4));
        wallBounce();
        turn(-30+Greenfoot.getRandomNumber(61));
        infect();
        youLost();
        

    } 
    public void wallBounce()
    {
        
        if(isAtEdge())
        {
            turn(180);
            changeColor();
            
            
        }
    }
    public void changeColor()
    {
        newColor = Greenfoot.getRandomNumber(2); //generate a new integer from 0-1 that will become new color
        while(newColor==imageNumber) //if new color is equal to old color
        {
            newColor = Greenfoot.getRandomNumber(2); //regenerates new color
        }
        imageNumber=newColor; // update current color of ball
        setImage("rbc-"+imageNumber+".png");
    }
    public boolean canSee(Class otherActor)
    {
        Actor actor = getOneObjectAtOffset(0,0, otherActor); //store an actor in variable if two images are mapped on to eachother
        if(actor !=null)
        { 
            return true;
        }
        else
        { 
            return false;
        }
    }
    public void infect()
    {
        if(canSee(Virus.class))
        {
           getWorld().removeObject(this);
           rbc--;
        } 
     
    }
    public void youLost()
    {
         if(rbc==0)
        {
           getWorld().showText("YOU LOST", 400, 300);
           Greenfoot.stop();
           rbc = 9;
  

        }
    }
}
Thanks
Mattzh Mattzh

2020/3/22

#
Lines 79 and 29 correspond to 21 and 71 respectively - I cut off the first few lines
danpost danpost

2020/3/23

#
Switch the order of lines 62 and 63; then move line 21 to be between those lines. The error was trying to show text on the null reference returned by getWorld, as the actor was removed from the world already.
You need to login to post a reply.