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

2012/12/22

A question about coding.

hkrhässleholm hkrhässleholm

2012/12/22

#
This codes are from the Crab class of greefoot book scenerios chapter 02-04 (little crab-2). import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) /** * This class defines a crab. Crabs live on the beach. They like sand worms * (very yummy, especially the green ones). * * Version: 2 * * In this version, the crab walks around the beach more or less randomly. */ public class Crab extends Animal { /** * Act - do whatever the crab wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { if ( atWorldEdge() ) { turn(17); } if ( Greenfoot.getRandomNumber(100) < 10 ) { turn( Greenfoot.getRandomNumber(90)-45 ); } { move(); } if(canSee(Worm.class)) { eat(Worm.class); } } } Okay, now my question is that if I write the "move( )" command (or method) after these lines instead of writing before the "if" statement then why the eat method doesn't execute in the scenerio ( I mean why my crab then doesn't eat any worm)? Ask me any further question if my question is not clear please..
vonmeth vonmeth

2012/12/22

#
Erm, can you show an example of the code you are using that is not working, as it should work, if I am understanding your explanation correctly.. There is no reason for there to be brackets around move();.
public class Crab extends Animal
{
    /** 
     * Act - do whatever the crab wants to do. This method is called whenever
     *  the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        if ( atWorldEdge() ) 
        {
            turn(17);
        }

        if ( Greenfoot.getRandomNumber(100) < 10 ) 
        {
            turn( Greenfoot.getRandomNumber(90)-45 );
        }
         move(); // no reason for brackets to be around this
        if(canSee(Worm.class))
        {
            eat(Worm.class);
        }
    }
}
You need to login to post a reply.