Can I use break on a nested for-loop to get back to outer while-loop and use continue
from inside the for-loop to force the while-loop to keep going? I can not get the for-loop conditions into my while-loop conditions so the while-loop might stop if I cannot continue on a specifically meet situation.
while(...some conditions...){
...print stuff
for(...some instances are arrays, condition loop array...){
if(...index meets conditions...){
...print once, some arrays might meet condition on multiple index
break; //to prevent multiple printings
}
continue; //i don't want to force another while iteration if(false)
//or is this continue for(loop) anyway?
}
continue; //is this not essentially a while(true) loop with no return?
}
The reason I can not get the for-loop conditions into the while conditions is because there are more if conditions between the two loops like if(array == null)
and if-condition x == true
getArray()
needs to be called if array is not passed in. Most of the time condition y
and z
print from while-loop but sometimes condition x
is met so I need the for-loop. It's after the printing of the for-loop if(index true))
I need the while-loop to go again that I'm stuck with? Sometime this might happen from while-loop conditions anyway but I can see that it wont always, further more if for-loop if(index false))
is meet I don't want to force the while loop as this could get costly in run time processing and could possibly result in an endless loop.
PS I am a junior programer, I'm not even sure it this is possible? or makes sense, sorry if its a stupid question
you can name your loops like this:
namedLoop: for(...) {
// access your namedloop
break namedLoop;
}
You can break
with label.
Here is a complete example showing it:
Basically the code is similar to this:
:myLabel
for (...) {
for(...) {
...
break myLabel; // Exit from both for loops
}
}
continue
and break
apply to the immediate current scope, so if you're inside the for
, it will apply to the for
.
You can store the comparison result on a boolean variable to check if you want to continue
.
I'm not a big fan of break
and continue
, it hinders readability in my opinion. You can acheive the same behavior using a different code structuring.
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.