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

2024/8/10

Need help with javaruntimeexception

endplasticbottles endplasticbottles

2024/8/10

#
My game I need help with this java exception. In Greenfoot the problem does not appear. The link above shows my game which throws the error.
danpost danpost

2024/8/10

#
endplasticbottles wrote...
<< Link Omitted >> I need help with this java exception. In Greenfoot the problem does not appear. The link above shows my game which throws the error.
I believe that it is the creating of the Counter object that is causing the problem (more specifically, when it is created). Use your MyWorld constructor to create the object. Try this (note lines 15 thru 18):
import greenfoot.*;

public class MyWorld extends World
{
    public static Counter counter;
    
    public static void addScore(int score)
    {
        counter.add(score);
    }

    public MyWorld()
    {    
        super(600, 400, 1);
        if (counter == null)
        {
            counter = new Counter();
        }
        addObject(counter, 521, 27);
        counter.setValue(0);
        addObject(new You(), 36, 374);
        for (int i=0; i<10; i++) {
            int randomX = 10 + Greenfoot.getRandomNumber(580);
            int randomY = 1 + Greenfoot.getRandomNumber(320);
            addObject(new PlasticBottle(), randomX, randomY);
        }
    }
}
The adding of bottles into the world during play (as well as prior to play) should be done by the World object (coded in your MyWorld class). The specific code to add a bottle could be put into a method of its own, so it can be used at both times. So, the for loop would be:
for (int i=0; i<10; i++)
{
    addBottle();
}
and the method would be:
public void addBottle()
{
    int randomX = 10 + Greenfoot.getRandomNumber(580);
    int randomY = 1 + Greenfoot.getRandomNumber(320);
    addObject(new PlasticBottle(), randomX, randomY);
}
endplasticbottles endplasticbottles

2024/8/31

#
Thanks that worked!
You need to login to post a reply.