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

2014/10/14

Code not working

Blackop778 Blackop778

2014/10/14

#
So I am doing this assignment for school and 1 line of code isn't working. Everything compiles correcty but when it runs it freezes every time it runs the line of code.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Fish here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Fish extends Animals
{
    public int Health;
    /**
     * Act - do whatever the Fish wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        move();
        Respawn();
        Fatality();
    }    
    public void Respawn()
    {
        if(atWorldEdgeforFish())
        {
            //This teleports the fish to either the same spot on the y-axis or a random spot
            //on the y-axis whenever a fish reaches the right edge of the world
            if(Greenfoot.getRandomNumber(3) == 1)
            {
                setLocation(0,getY());
                Health++;
            }
            else
            {
                setLocation(0,Greenfoot.getRandomNumber(getWorld().getHeight() + 1));
                Health++;
            }
        }
    }
    public void Fatality()
    {
        //this will remove fish after a certain number of laps and then add a new fish in
        if(Health >= 7 + Greenfoot.getRandomNumber(4) && Greenfoot.getRandomNumber(21) == 1)
        {
            getWorld().removeObject(this);
            getWorld().addObject(new Fish(), 0, 0);
        }
    }
}
The line getWorld().addObject(new Fish(), 0, 0); is what isn't working.
Blackop778 Blackop778

2014/10/14

#
I can post the error message if it would help
Super_Hippo Super_Hippo

2014/10/14

#
Switch line 45 and 46. In line 45, you remove the object. Then, in line 46, you are trying to get the world which returns a nullpointer exception. So add the new fish, before you remove the current one. Btw, what do you want to do there? Why do you add a new fish and remove the current one instead of doing something like:
setLocation(0,0);
Health = 0;
Oh, and especially when it is for school: Names of methods and variables should start with a small letter.
danpost danpost

2014/10/14

#
Blackop778 wrote...
I can post the error message if it would help
I am sure you are throwing a 'NullPointerException'. You have the fish that runs this code being removed from the world on line 45. So, 'getWorld' on line 46 will return 'null' -- and you cannot call the World instance method 'addObject' on 'null'. You can either add the new fish before removing 'this' or you can just relocate 'this' fish to (0, 0) using 'setLocation'.
Blackop778 Blackop778

2014/10/16

#
Yep it works. Thanks guys!
You need to login to post a reply.