[英]Break out of nested for loop without using break statement
我想脫離嵌套的for循環而不使用break
語句。 原因是在稍后使用break
語句時在程序中出現問題。
源代碼是這樣的:
for (int i = 0; i < 100; i++){
for (int j = 10; j < 100; j++) {
code;
if (code == true) {
:break out here:
}
}
}
那是goto語句不會很糟糕的少數情況之一。 更好的是,將循環提取到另一種方法中並使用return語句,如@SR SH所述。
嘗試這樣做,這很簡單。
boolean flag = true;
for (int i = 0; i < 100; i++){
for (int j = 10; j < 100; j++) {
code;
if (code == true) {
j = 101; //any value that would make the condition check in for loop false
flag = false;
}
}
if (flag==false) {
i = 101; //any value that would make the condition check in for loop false
}
}
另一種可能性是使用布爾標志,該標志被添加到for循環的條件中。
boolean breakOut = false;
for (int i = 0; i < 100 && !breakOut; i++) {
for (int j = 10; j < 100 && !breakOut; j++) {
code;
if (code == true) {
breakOut = true;
}
}
}
for(int i = 0; i < 100; i++){
for (int j = 10; j < 100; j++) {
//code;
if(code == true){
j = 100; //will cancel the inner for loop.
}
}
}
根據要中斷的循環,使i和/或j大於100
對此進行更改。
public void firstFor(int index){
for(int i =index; i<100;i++){
secondFor();
}
}
public void secondFor(){
for(int j=0;j<100;j++){
//your code...
if(code==true) return;
}
}
將您的代碼塊放在單獨的方法中,然后使用return。 這將是最干凈的方法。
您可以使用標簽:
firstLabel: for (int i = 0; i < 100; i++) {
secondLabel: for (int j = 10; j < 100; j++) {
System.out.println("J = " + j);
if (j == 50) {
break firstLabel;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.