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

2020/3/2

My Code LØØps?

DecentRug03 DecentRug03

2020/3/2

#
I am having some troubles with my code. I programmed it how I know and what my professor told me but my code won't execute. I went into the code with the debugger and it just keeps looping on the MyWorld class and I don't know if I did something wrong or not. Help would be appreciated, Thanks.
import greenfoot.*;
public class MyWorld extends World
{
    public MyWorld()
    {    
        super(600, 400, 1); 
    }
    public void act(int heads, int tails, int num)
    {
        num = Greenfoot.getRandomNumber(1);
        if (num == 1)
        {
            heads++;
        }
        else
        {
            if(num == 0)
            {
                tails++;
            }
        }
        while ( heads + tails != 50 )
        {
            num = Greenfoot.getRandomNumber(1);
        }
        showText("Number Of Heads "+heads, 300, 200);
        showText("Number Of Tails "+tails, 300, 190);
    }
}
danpost danpost

2020/3/3

#
The while loop, lines 22 thru 25, is the reason. If the condition is ever true, which would start the loop, nothing will happen during the execution of the loop to make the condition false. In fact, the condition is true from the start; so, as soon as you execute an act method (or run the scenario) it will get caught in the loop "indefinitely". I think you just want the following from line 22 on:
if (heads + tails == 50)
{
    showText("Number of Heads "+heads, 300, 200);
    showText("Number of Tails "+tails, 300, 190);
    heads = 0;
    tails = 0;
}
or, something to that effect.
DecentRug03 DecentRug03

2020/3/3

#
But I need to have a while loop in there. Also, like I said, I looked in the debugger and it is looping on the "public MyWorld()..." part. I don't think it was something in my code but thanks for letting me know to initialize heads and tails.
danpost danpost

2020/3/4

#
If you are to use a while loop, then somewhere inside the loop you must eventually have that condition become false. Since the only two variables in your while condition are heads and tails, one or both of their values must change within the loop so that eventually the condition will not be true. Also, this line:
num = Greenfoot.getRandomNumber(1);
will always set num to zero, since you only give it that "1" choice.
danpost danpost

2020/3/4

#
DecentRug03 wrote...
But I need to have a while loop in there.
Why?
You need to login to post a reply.