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

2013/4/2

why does my for-loop create only one object instead of three?

Joep Joep

2013/4/2

#
Hi. I have this bit of code in my constructor for a world
public void startGame()
    {
        Fly fly = new Fly();
        addObject(fly , getWidth()/2 +100, getHeight()/2);
        
        BarLife barLife = new BarLife(200 , fly);
        addObject(barLife , 112 , 15);
        
        Enemy spider = new Spider();
        for(int i=0 ; i<3 ; i++)
        {
            int x = Greenfoot.getRandomNumber( getWidth() );
            int y = Greenfoot.getRandomNumber( getHeight() );
            addObject(spider , x , y);
        }
        
    }
and it should create three object of the class spider, but only creates one. Does sombody know why this is happening? I'm fairly new to programming, so i think the solution will be very simple
JetLennit JetLennit

2013/4/2

#
now, why don't you have it be
int x = Greenfoot.getRandomNumber( getWidth() );
            int y = Greenfoot.getRandomNumber( getHeight() );
            addObject(spider , x , y);
int x = Greenfoot.getRandomNumber( getWidth() );
            int y = Greenfoot.getRandomNumber( getHeight() );
            addObject(spider , x , y);
int x = Greenfoot.getRandomNumber( getWidth() );
            int y = Greenfoot.getRandomNumber( getHeight() );
            addObject(spider , x , y);
davmac davmac

2013/4/2

#
You create one new spider on line 9: Enemy spider = new Spider(); Then you have a for loop which attempts to add the spider to the world. But if you add an object into the world when that object is already in the world, it has no effect (other than maybe moving the object). You need to put the above line inside the for-loop body.
You need to login to post a reply.