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

2014/4/13

How to get more leafs if a wombat ate one? (Beginner)

name68 name68

2014/4/13

#
Hello, I have a question and I am beginner as you can see. My plan: If a Wombat eats a Leaf, the Programm creates new leafs automatically. I hope you understand what I try to ask. Here is my code. If I try this code, I do not get an message that the code is wrong. But if the wombat eats a leaf, the programm does not automatically create new leafs. Here is my code that does not really work:
    public void act()
    {
        if(Leaf.class == null)
        {
            addObject(new Leaf(),Greenfoot.getRandomNumber(560),Greenfoot.getRandomNumber(560)); 
        }
    }  
Thank you for help!
danpost danpost

2014/4/13

#
You are asking the wrong question (that is, using the wrong condition in the 'if' statement). You want to use:
if (getObjects(Leaf.class).isEmpty())
erdelf erdelf

2014/4/13

#
well, u wrote that if the class is equal to null, it should create a new leaf where ist the code you posted`? Edit: or just hear on danpost, we wrote at the same time
danpost danpost

2014/4/13

#
danpost wrote...
You are asking the wrong question (that is, using the wrong condition in the 'if' statement). You want to use:
if (getObjects(Leaf.class).isEmpty())
This will ensure that at least one leaf is in the world. If you want to place a minimum limit on the number of leaves:
if (getObjects(Leaf.class).size() < /** minimum limit */)
name68 name68

2014/4/13

#
Thank you so much, it works now! Could you please explain to me, why what I wrote was incorrect? That would be really nice of you!
danpost danpost

2014/4/13

#
You wrote:
if (Leaf.class == null)
Well, 'Leaf.class' refers to the class itself -- not to any objects created from that class. You do have a Leaf class and it is not null -- ever; unless you removed the class -- in which case you would not be able to create any Leaf objects. In fact, it would not even compile if you did not have a Leaf class and tried to refer to it. On the other hand -- what 'getObjects(Class cls)' does is creates a List object containing any and all objects of the given class that are in the world. The list has a size (the number of those objects in the world) and that size could be zero; in which case the List object would be empty (it is still a List, so do not ask if the List object is null; and all elements of the list, if any, will contain an object of the given type, so none of them will be null either).
name68 name68

2014/4/13

#
Thank You for Your explanation!
You need to login to post a reply.