1

如果彼此内部有 3 个循环,我怎么能中断到上层循环,我的意思是:

while (abc) {
    for (int dep =0 ; dep<b ; dep++)  {
         for (int jwe=0 ; jwe<g ; jwe++) {
             if (! (ef || hf) ) {
             //here is where i want to break to loop while
             //or in other purpose (other situation) i need 
             //to know how i could break to first loop  
             //i mean (for (int dep =0 ; dep< b ; dep++)
             }
         }
    }
} 

有人可以帮我吗,如果之后,我可以如何中断到while循环,或者我如何可以中断到第一个循环“for”。

4

6 回答 6

4

只需将外部循环的计数器设置为一个不会再次运行的值。

while (abc) {
    for (int dep =0 ; dep<b ; dep++)
    for (int jwe=0 ; jwe<g ; jwe++)
     if (! (ef || hf) ) {
         //here is where you want to break to the while-loop
         //abc = 0; here will make it exit the entire while as well
         dep = b; //in order to exit the first for-loop
         break;
     }
} 
于 2013-03-02T22:24:35.970 回答
2

这是goto结构最清晰的(罕见)情况之一:

while (abc) {
    for (int dep =0 ; dep<b ; dep++)  {
         for (int jwe=0 ; jwe<g ; jwe++) {
             if (! (ef || hf) ) {
                 // Do anything needed before leaving "in the middle"
                 goto out;
             }
         }
    }
}
out:
// Continue here

确保缩进不会隐藏标签。

于 2013-03-02T22:43:14.033 回答
0
continue_outer_loop = true;
while (abc) {

  for ( int i = 0; i < X && continue_outer_loop; i++) {
    for ( int j = 0; j < Y; j++ {

       if (defg) {
         continue_outer_loop = false;  // exit outer for loop
         break;                        // exit inner for loop
       }

    }
  }
}
于 2013-03-02T22:35:21.607 回答
0

一些语言(包括 Java)支持打破标签:

outerLoop: // a label
while(true) {
   for(int i = 0; i < X; i++) {
      for(int j = 0; j < Y; j++) {
         // do stuff 
         break outerLoop; // go to your label
      }
   }
}
于 2013-03-02T22:27:16.550 回答
0
int breakForLoop=0;
    int breakWhileLoop=0;
    while (abc) {

        for (int dep = 0;dep < b;dep++) {

            for (int jwe = 0;jwe < g; jwe++) {


                if (!(ef || hf)) {
                    breakForLoop=1;
                    breakWhileLoop=1;
                    break;

                }
            }
            if(breakForLoop==1){
                break;
            }
        }
        if( breakWhileLoop==1){
                break;
            }
    } 
于 2013-03-02T22:29:12.217 回答
0

例如,使用int变量int terminate = 0;并将其与您的条件一起放入 while 循环中while(true && terminate == 0)。如果要中断外循环,请1在从内循环中断之前将变量设置为。

于 2013-03-02T22:30:42.310 回答