GoTo Next Iteration in For Loop in java

后端 未结 6 1573
悲&欢浪女
悲&欢浪女 2020-12-22 23:24

Is there a token in java that skips the rest of the for loop? Something like VB\'s Continue in java.

6条回答
  •  独厮守ぢ
    2020-12-22 23:49

    If you want to skip current iteration, use continue;.

    for(int i = 0; i < 5; i++){
        if (i == 2){
            continue;
        }
     }
    

    Need to break out of the whole loop? Use break;

    for(int i = 0; i < 5; i++){
        if (i == 2){
            break;
        }
    }
    

    If you need to break out of more than one loop use break someLabel;

    outerLoop:                                           // Label the loop
    for(int j = 0; j < 5; j++){
         for(int i = 0; i < 5; i++){
            if (i==2){
              break outerLoop;
            }
         }
      }
    

    *Note that in this case you are not marking a point in code to jump to, you are labeling the loop! So after the break the code will continue right after the loop!

    When you need to skip one iteration in nested loops use continue someLabel;, but you can also combine them all.

    outerLoop:
    for(int j = 0; j < 10; j++){
         innerLoop:
         for(int i = 0; i < 10; i++){
            if (i + j == 2){
              continue innerLoop;
            }
            if (i + j == 4){
              continue outerLoop;
            }
            if (i + j == 6){
              break innerLoop;
            }
            if (i + j == 8){
              break outerLoop;
            }
         }
      }
    

提交回复
热议问题