[英]How to break continue a nested for-loop inside a while-loop?
我可以在嵌套的for循環中使用break來返回外部while循環並在for循環中使用continue
來強制while循環繼續運行嗎? 我無法將for循環條件納入我的while循環條件,因此如果我無法繼續特定的滿足情況,則while循環可能會停止。
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?
}
我無法將for循環條件轉換為while條件的原因是因為如果兩個循環之間的條件更多,如if(array == null)
和if-condition x == true
需要調用getArray()
數組沒有傳入。大部分時間條件y
和z
從while循環打印,但有時條件x
滿足,所以我需要for循環。 它是在打印for循環之后的if(index true))
我需要while循環才能再次進入我的狀態? 有時這可能發生在while循環條件下但是我可以看到它不會總是,如果for循環if(index false))
滿足更多我不想強制while循環,因為這可能會在運行中變得昂貴時間處理,可能會導致無限循環。
PS我是一名初級程序員,我甚至不確定這是可能的嗎? 或者說有道理,抱歉,如果這是一個愚蠢的問題
你可以這樣命名你的循環:
namedLoop: for(...) {
// access your namedloop
break namedLoop;
}
你可以break
標簽。
這是一個顯示它的完整示例:
基本上代碼類似於:
:myLabel
for (...) {
for(...) {
...
break myLabel; // Exit from both for loops
}
}
continue
和break
適用於當前范圍,因此如果你在for
,它將適用於for
。
您可以將比較結果存儲在布爾變量中,以檢查是否要continue
。
我不是一個大風扇的break
和continue
,它阻礙了可讀性,在我看來。 您可以使用不同的代碼結構來實現相同的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.