欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java中for循环中执行顺序问题及break, continue标签用法

程序员文章站 2024-03-23 18:46:40
...
public class labeledfor {
  static test monitor = new test();
  public static void main(string[] args) {
      int i = 0;
      outer: // can't have statements here
      for(; true ;) { // infinite loop
           inner: // can't have statements here
           for(; i < 10; i++) {
                system.out.println("i = " + i);
                if(i == 2) {
                    system.out.println("continue");
                    continue;
                }
                if(i == 3) {
                    system.out.println("break");
                    i++; // otherwise i never
                          // gets incremented.
                    break;
                }
                if(i == 7) {
                    system.out.println("continue outer");
                    i++; // otherwise i never
                           // gets incremented.
                    continue outer;
                }
                if(i == 8) {
                    system.out.println("break outer");
                    break outer;
                }

                for(int k = 0; k < 5; k++) {
                    if(k == 3) {
                         system.out.println("continue inner");
                         continue inner;
                    }

 结果:
"i = 0",
"continue inner",
"i = 1",
"continue inner",
"i = 2",
"continue",
"i = 3",
"break",
"i = 4",
"continue inner",
"i = 5",
"continue inner",
"i = 6",
"continue inner",
"i = 7",
"continue outer",
"i = 8",
"break outer"

总结:

  (1):一般的continue会退回最内层循环的开头(顶部),并继续执行。
  (2):带标签的continue会到达标签的位置,并重新进入紧接在那个标签后面的循环。
  (3):一般的break会中断并跳出当前的循环。
  (4):带标签的break会中断并跳出标签所指的循环。
要记住的重点是:在Java里面需要使用标签的唯一理由是因为有循环嵌套的存在,而且像从多层嵌套中break或continue。