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

2013/9/19

Act method executes only the first block of code!!!

preeti preeti

2013/9/19

#
i am writing a code to simulate a gumball machine scenario. but the ac method is getting executed partly!! Only the block of code pertaining to penny gets executed!! and if i copy-paste the fakeQuarter code before the penny code, then only the fakeQuarter code gets executed!! so basically only the first block of code is getting executed.. import greenfoot.*; public class GumballMachine extends Actor { public GumballMachine() { GreenfootImage image = getImage() ; image.scale( 350, 400 ) ; } public void act() { Penny penny = (Penny) getOneObjectAtOffset(0, 0, Penny.class); if(penny==null) { return; } else { getWorld().removeObject(penny); for(Object obj : getWorld().getObjects(Inspector.class)) { Inspector inspector = (Inspector) obj; inspector.call("HAVE COIN!"); } } FakeQuarter fakeQuarter = (FakeQuarter) getOneObjectAtOffset(0,0,FakeQuarter.class); if(fakeQuarter==null) { return; } else { getWorld().removeObject(fakeQuarter); for(Object obj : getWorld().getObjects(Inspector.class)) { Inspector inspector1 = (Inspector) obj; inspector1.call("HAVE COIN!"); } } } }
davmac davmac

2013/9/19

#
You have:
if(penny==null)
{
    return;
}
The 'return' causes the act method to finish executing and return to the caller. If you want the execution to continue, you shouldn't use return here. Instead you could for eg:
public void act()
{
    Penny penny = (Penny) getOneObjectAtOffset(0, 0, Penny.class);
    if(penny != null)
    {
        getWorld().removeObject(penny);
        for(Object obj : getWorld().getObjects(Inspector.class))
        {
            Inspector inspector = (Inspector) obj; inspector.call("HAVE COIN!");
        }
    }

    FakeQuarter fakeQuarter = (FakeQuarter) getOneObjectAtOffset(0,0,FakeQuarter.class);
    // etc
Please use 'code' tags around your code in posts here. It's very difficult to copy and edit otherwise.
You need to login to post a reply.