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

2018/2/6

Counting a class' objects

MirunaTele MirunaTele

2018/2/6

#
Hi! How can I count how many objects I have in onw class? I added the objects in My World editor, with a while loop, and I counted the objects in the i variable, but I can't use this variable in other editor.
int i=0;
        int x=Greenfoot.getRandomNumber(600);
        int y=Greenfoot.getRandomNumber(400);
        
        
        while (i<5)
        {
            addObject (new Alien(),x,y);
            i++;
        
            addObject (new Planet (), x+Greenfoot.getRandomNumber(200), y+Greenfoot.getRandomNumber(200));
            x=Greenfoot.getRandomNumber(600);
            y=Greenfoot.getRandomNumber(400);
            
            if (x==100)
            {
                while (x==100)
                {x=Greenfoot.getRandomNumber(600);}
            }
            if (y==200)
            {
                while (y==200)
                {y=Greenfoot.getRandomNumber(400);}
            }
        }
Vercility Vercility

2018/2/6

#
Create a public method that returns I and call it from the other class
Super_Hippo Super_Hippo

2018/2/6

#
The 'getObjects' method can be used on a world object to get a list of all objects or all objects of one class. The size of that list is the number of objects of the specified class (or all) which are currently in this world.
MirunaTele MirunaTele

2018/2/7

#
Thanks very much!
You need to login to post a reply.