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

2016/10/27

Stop loop if condition is not met anymore?

ChristianStachelhaus ChristianStachelhaus

2016/10/27

#
So is there a way to jump out of a loop that is being executed instantly after the condition isn't met anymore? Because a while loop is executing 'till the end of the loop, even if the condition isn't met anymore, right? For example: normal while loop:
        while(condition())
        {
            instruction1;
            instruction2;
            instruction3;
            instruction4;
            instruction5;
        }
what i want:
        while(condition())
        {
            instruction1();
            checkcondition();       //if condition is met, go on, if it isn't break out of the loop
            instruction2();
            checkcondition();
            instruction3();
            checkcondition();
            instruction4();
            checkcondition();
            instruction5();
        }
I know that I could do this by putting every instruction into a if loop, but thats pretty confusing and its getting the method pretty big if I got a lot of instructions. Is there a easier way to do it?
danpost danpost

2016/10/28

#
What you want is (maybe):
for (int i=0; checkCondition(); i++)
{
    switch(i)
    {
        case 0:  instruction1(); break;
        case 1:  instruction2(); break;
        // etc.
        default: i = -1;
    }
}
ChristianStachelhaus ChristianStachelhaus

2016/10/28

#
Well, this is a pretty smart solution that i never had thinked of! Thank you, I will test this as soon as i get home.
danpost danpost

2016/10/29

#
Another way might be that you make all your instruction methods return a boolean value and place the following line at the end of each one:
return checkCondition();
Then, your code would look like this:
while (instruction1() && instruction2() && instruction3() && instruction4() && instruction5()) ;
The semi-colon at the end of the while loop acts as an empty block of code to execute (no operations).
You need to login to post a reply.