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

2015/4/3

Need help urgently! Stuck in infinite loop

DialUp DialUp

2015/4/3

#
Hey guys I need help asap. I been spending 8 hours on this and I can't figure it out, I'm using a world called MyClara and I am stuck in a infinite loop. My object is to follow a trail of leafs, and collect those leafs. After I have collected those leafs, Clara stops, but she keeps continuing and I have no idea why. These are the commands I can use: And here is my code: public void run() { // TODO: Write your code below while(onLeaf()) { removeLeaf(); move(); if(!onLeaf()) { getBackOnTrack(); } } } public void getBackOnTrack() { turnLeft(); turnLeft(); move(); turnRight(); move(); } } • turnLeft(); - Clara turns 90 degrees to the left • move() - Clara moves one step forward in the direction she is currently facing • putLeaf() - Clara puts one leaf at her current position • removeLeaf(); - Clara removes a leaf at her current position • stop(); - Has the same effect as pressing the “pause” button • turnRight(); - Clara turns 90 degrees to the right • onLeaf(); - Returns true if Clara is positioned on top of a leaf or false otherwise • treeFront(); - Returns true if there is a tree one step ahead in the direction Clara faces or false otherwise • treeLeft(); - Returns true if there is a tree to the left from Clara or false otherwise • treeRight(); - Returns true if there is a tree to the right from Clara or false otherwise • mushroomFront(); Returns true if there is a tree to the right from Clara or false otherwise We can also use For loops, and while loops and if statements and such. Here is the photo of what you need to achieve [Disallowed URL]
Super_Hippo Super_Hippo

2015/4/3

#
randombruh randombruh

2015/4/4

#
Yeah thanks for help I had to make another account cause it got detected for spam i edited it 2 times. I couldn't wait I was in a rush so I had to make new account.
danpost danpost

2015/4/4

#
Using only the methods given above (with loops and ifs, etc), there is no shortcut way to detect when to call 'stop'. Therefore, you must code 'if' within 'if' for each direction until either a leaf is found to eat or all directions are exhausted. Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
while (true)
{
    if (atLeaf()) // first location check
    {
        eatLeaf();
        move();
    }
    else
    {
        turnLeft();
        turnLeft();
        move();
        turnRight();
        move();
        // repeat lines 3 through 14 here -- second location check
            // repeat lines 3 through 14 here -- third location check
                // repeat lines 3 through 9 here -- last location check
                    stop();
                    break; // exits loop (to exit method)
                }
            }
        }
    }
}
You need to login to post a reply.