I would like to have a while loop that if a certain condition is true, do not do the code below it and then continue with the while loop. Here is some psuedocode:
boolean poop
while (poop){
if (player.isAwesome()){
Continue doing while loop but do not execute below code
}
poop = false;
}
Yes, I can use something like this:
boolean poop
while (poop){
boolean stopPoop = false;
if (player.isAwesome()){
stopPoop = true;
}
if (!stopPoop){
poop = false;
}
}
However, that is sort of messy and inconvenient, and I was wondering if there is a better way?
boolean poop = true;
while (poop){
if (player.isAwesome()){
//Continue doing while loop but do not execute below code
continue;
}
poop = false;
}
Yes, that's right use the continue
keyword. If you wanted to break out of the loop you could use the break
keyword
If you have nest loops then you can also continue to a label.
I don't see the need for the poop variable. can't you just use this.
while (player.isAwesome()){
Continue doing while loop but do not execute below code
}
In cases such as these where it is difficult to predict when a loop should be terminated, I prefer to use
do {
if (player.isAwesome()){
//Continue doing while loop but do not execute below code
continue;
}
// This code will only execute once
} while (false);
This removes the need for the boolean flag which pollutes the scope outside the loop.
I discourage for (;;)
or while (true)
since, over time, maintenance of code written in this way can introduce infinite looping.
I assume you are using java for coding. All you need to do is write
continue;
at the line you need to go to the while loop check statement. So:
boolean poop
while (poop){
if (player.isAwesome()){
continue;
}
poop = false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.