标签:
label1:
label1: outer-iteration{ inner-iteration{ //... break;//(1) //... continue;//(2) //... continue label1;//(3) //... break label1;//(4) } }在(1)中,break中断内部迭代,回到外部迭代。在(2)中,continue使执行点移回内部迭代的起始处。在(3)中,continue label1同时中断内部迭代及外部迭代,直接转到label1处;随后,它实际上是继续迭代过程,但却从外部迭代开始。在(4)中,break label1也会中断所有迭代,并回到label1处,但并不重新进入迭代。也就是说,它实际是完全中止了两个迭代。
package com.mufeng.thefourthchapter; public class Labeled { public static void main(String[] args) { System.out.println("标签用于for循环的例子"); 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 否则i不会得到增量 break; } if (i == 7) { System.out.println("continue outer"); i++;// Otherwise i never gets incremented 否则i不会得到增量 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; } } } } System.out.println("标签用于while循环的例子"); i = 0; outer: while (true) { System.out.println("Outer while loop"); while (true) { i++; System.out.println("i = " + i); if (i == 1) { System.out.println("continue"); continue; } if (i == 3) { System.out.println("continue outer"); continue outer; } if (i == 5) { System.out.println("break"); break; } if (i == 7) { System.out.println("break outer"); break outer; } } } } }
标签用于for循环的例子 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 标签用于while循环的例子 Outer while loop i = 1 continue i = 2 i = 3 continue outer Outer while loop i = 4 i = 5 break Outer while loop i = 6 i = 7 break outer
Java 中break和continue结合标签标示符中断循环示例详解(附源码)
标签:
原文地址:http://blog.csdn.net/u013693649/article/details/51691793