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

2017/1/18

need help with nullpointerexceptions

brothermic brothermic

2017/1/18

#
hello, i had some double code in my classes. so i wanted to put some code in the superclass. however after tons of nullpointerexceptions i started to take it step by step. i will show here my code of a monster: firemonster and the superclass : Enemys. and i'll post the nullpointerexception. idont have an idea what the problem might be.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Write a description of class Enemys here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Enemys extends ScrollActors
{
    private boolean allowFire;
    private MyWorld world;
    private boolean isAlive;

    public Enemys()
    {
        allowFire = false;
        if(getWorld() instanceof MyWorld){
            world = (MyWorld) getWorld();
        }
        isAlive = true;
    }

    /**
     * Act - do whatever the Enemys wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        turnToTank();
        move(1);
        if(isTouching(Obstacles.class)){
            move(-10);
            turn(Greenfoot.getRandomNumber(180));
        }
        if(Greenfoot.getRandomNumber(30) < 1){
            turn(Greenfoot.getRandomNumber(91));
        }
        removeDead();
    }

    public void turnToTank()
    {
        List<Tank> tank = getObjectsInRange(170, Tank.class);
        if( !tank.isEmpty()){
            Tank myTank = tank.get(0);
            turnTowards(myTank.getX(), myTank.getY());
            allowFire = true;
        }
        else {
            allowFire = false;
        }
    }

    public boolean getAllowFire()
    {
        return allowFire;
    }

    public void addScore(int amountPoints)
    {
        Counter counter = world.getCounter();
        counter.add(amountPoints);

    }

    public void die(MedKit medKit)
    {

        if(Greenfoot.getRandomNumber(3) == 2){
            world.addObject(medKit,getX(),getY());
        }
        isAlive = false;
    }
    
    public void removeDead()
    {
        if(!isAlive){
            world.removeObject(this);
        }
    }
    
    public void markDead()
    {
        isAlive = false;
    }
that was the superclass enemys following is the subclass firemonster
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Firemonster here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Firemonster extends Enemys
{
    private int hp; // healthpoints
    private int fireBallCastingTime; //time it takes to cast fireball
    private int castDelayCount; //time since last casting a fireball
    private HealthBar healthBar;
    private int maxHp;
    private static final int POINTS = 250;
    public Firemonster()
    {
        super();
        hp = 1000;
        fireBallCastingTime = 20;
        castDelayCount = 0;
        maxHp = 1000;
        healthBar = null;
    }

    /**
     * Act - do whatever the Firemonster wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        super.act();
        addHealthBarAndUpdate();
        setImage();
        castDelayCount++;
        shootFireBall();
        checkStatus();
    } 

    public void setImage()
    {
        String[] image = {"FireMonster0.png","FireMonster1.png","FireMonster2.png","FireMonster3.png","FireMonster4.png","FireMonster5.png","FireMonster6.png","FireMonster7.png","FireMonster6.png","FireMonster6.png"};
        int[][] rotation = {
                {113,158,203,248,293,332,23,68,23,359},
                {68,113,158,203,248,293,332,23,0,332}
            };
        for(int teller = 0; teller < image.length; teller++){
            if(getRotation() < rotation[0][teller] && getRotation() >= rotation[1][teller]){  
                setImage(image[teller]);
                getImage().rotate(-getRotation());
            }
        }

    }

    public void checkStatus()
    {
        MyWorld world = (MyWorld) getWorld();
        Counter counter = world.getCounter();
        if(hp <= 0){
            if(Greenfoot.getRandomNumber(3) == 2){
                world.addObject(new MedKit() ,getX(),getY());
            }
            counter.add(POINTS);
            markDead();
        }

    }

    public void hit(int damageTaken)
    {
        hp = hp - damageTaken;
    }

    private void shootFireBall()
    {
        if(getAllowFire() == true){
            if(castDelayCount >= fireBallCastingTime){
                getWorld().addObject(new Fireball(getRotation()),getX(),getY());
                castDelayCount = 0;
            }
        }
    }

    private void addHealthBarAndUpdate()
    {

        if(healthBar == null){
            healthBar = new HealthBar(hp,maxHp);
            getWorld().addObject(healthBar,getX(), getY()- 28);

        }
        healthBar.update(getX(), getY() -28, hp);
    }
}
and the error : at greenfoot.core.Simulation.runOneLoop(Simulation.java:562) at greenfoot.core.Simulation.runContent(Simulation.java:221) at greenfoot.core.Simulation.run(Simulation.java:211) java.lang.NullPointerException at Enemys.removeDead(Enemys.java:79) at Enemys.act(Enemys.java:39) at Icemonster.act(Icemonster.java:32) at greenfoot.core.Simulation.actActor(Simulation.java:604) at greenfoot.core.Simulation.runOneLoop(Simulation.java:562) at greenfoot.core.Simulation.runContent(Simulation.java:221) at greenfoot.core.Simulation.run(Simulation.java:211) java.lang.NullPointerException at Enemys.removeDead(Enemys.java:79) at Enemys.act(Enemys.java:39) at Icemonster.act(Icemonster.java:32) at greenfoot.core.Simulation.actActor(Simulation.java:604) at greenfoot.core.Simulation.runOneLoop(Simulation.java:562) at greenfoot.core.Simulation.runContent(Simulation.java:221) at greenfoot.core.Simulation.run(Simulation.java:211)
Zamoht Zamoht

2017/1/18

#
The first thing that comes to mind is that world is never set to anything if the monster is placed in another world than MyWorld. Are you using multiple worlds? Line 18 in Enemys is the problem if this is the case.
brothermic brothermic

2017/1/18

#
got only 1 world : MyWorld (subclass from Word defined by greenfoot). However my errors desappeared once i removed the removeDead() method from the superclass enemys to the sublass firemonster. So i decided to proceed and put more code from firemonster into enemys: i want to just call a method called die(parameter drop) in my firemonster and the method is described in enemys (superclass) but again i get errors: code enemys:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List;
/**
 * Write a description of class Enemys here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Enemys extends ScrollActors
{
    private boolean allowFire;
    private MyWorld world;
    private boolean isAlive;
    

    public Enemys()
    {
        allowFire = false;
        isAlive = true;
        world = (MyWorld) getWorld();
    }

    /**
     * Act - do whatever the Enemys wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        turnToTank();
        move(1);
        if(isTouching(Obstacles.class)){
            move(-10);
            turn(Greenfoot.getRandomNumber(180));
        }
        if(Greenfoot.getRandomNumber(30) < 1){
            turn(Greenfoot.getRandomNumber(91));
        }
        
    }

    public void turnToTank()
    {
        List<Tank> tank = getObjectsInRange(170, Tank.class);
        if( !tank.isEmpty()){
            Tank myTank = tank.get(0);
            turnTowards(myTank.getX(), myTank.getY());
            allowFire = true;
        }
        else {
            allowFire = false;
        }
    }

    public boolean getAllowFire()
    {
        return allowFire;
    }

    public void addScore(int amountPoints)
    {
        Counter counter = world.getCounter();
        counter.add(amountPoints);

    }

    public void die(MedKit medKit)
    {
        if(Greenfoot.getRandomNumber(3) == 2){
            world.addObject(medKit,getX(),getY());
        }
        isAlive = false;
    }

    public void removeDead()
    {
        if(!isAlive){
            world.removeObject(this);
        }
    }
and this is code firemonster :
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Firemonster here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Firemonster extends Enemys
{
    private int hp; // healthpoints
    private int fireBallCastingTime; //time it takes to cast fireball
    private int castDelayCount; //time since last casting a fireball
    private HealthBar healthBar;
    private int maxHp;
    private static final int POINTS = 250;
    public Firemonster()
    {
        super();
        hp = 1000;
        fireBallCastingTime = 20;
        castDelayCount = 0;
        maxHp = 1000;
        healthBar = null;
    }

    /**
     * Act - do whatever the Firemonster wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        super.act();
        addHealthBarAndUpdate();
        setImage();
        castDelayCount++;
        shootFireBall();
        checkStatus();
        removeDead();
    } 

    public void setImage()
    {
        String[] image = {"FireMonster0.png","FireMonster1.png","FireMonster2.png","FireMonster3.png","FireMonster4.png","FireMonster5.png","FireMonster6.png","FireMonster7.png","FireMonster6.png","FireMonster6.png"};
        int[][] rotation = {
                {113,158,203,248,293,332,23,68,23,359},
                {68,113,158,203,248,293,332,23,0,332}
            };
        for(int teller = 0; teller < image.length; teller++){
            if(getRotation() < rotation[0][teller] && getRotation() >= rotation[1][teller]){  
                setImage(image[teller]);
                getImage().rotate(-getRotation());
            }
        }

    }

    public void checkStatus()
    {
        MyWorld world = (MyWorld) getWorld();
        Counter counter = world.getCounter();
        if(hp <= 0){
            counter.add(POINTS);
            die(new MedKit());
        }

    }

    public void hit(int damageTaken)
    {
        hp = hp - damageTaken;
    }

    private void shootFireBall()
    {
        if(getAllowFire() == true){
            if(castDelayCount >= fireBallCastingTime){
                getWorld().addObject(new Fireball(getRotation()),getX(),getY());
                castDelayCount = 0;
            }
        }
    }

    private void addHealthBarAndUpdate()
    {

        if(healthBar == null){
            healthBar = new HealthBar(hp,maxHp);
            getWorld().addObject(healthBar,getX(), getY()- 28);

        }
        healthBar.update(getX(), getY() -28, hp);
    }
}
methods to look at are in firemonster (subclass) ---> checkstatus() and in superclass enemys ---> die(MedKit medKit) the errors are : java.lang.NullPointerException at Enemys.die(Enemys.java:69) at Firemonster.checkStatus(Firemonster.java:64) at Firemonster.act(Firemonster.java:38) at greenfoot.core.Simulation.actActor(Simulation.java:604) at greenfoot.core.Simulation.runOneLoop(Simulation.java:562) at greenfoot.core.Simulation.runContent(Simulation.java:221) at greenfoot.core.Simulation.run(Simulation.java:211)
Super_Hippo Super_Hippo

2017/1/18

#
The constructor is executed when the object is created, before it is added to the world. That's why your 'world' variable is never anything else then 'null'. If you really want to save a reference to the world in your enemy class, you can add the 'addedToWorld' method:
protected void addedToWorld(World w)
{
    world = (MyWorld) w;
}
Maybe you can also use this (try it out, I am not sure):
protected void addedToWorld(MyWorld w)
{
    world = w;
}
You need to login to post a reply.