作用:在循环里,配合continue,方便跳出循环
Example:
不防来做一个简单的算法题:
输出一百以内的所有素数。(素数:只有能被1和自己整除的数,如2,3,5,7.。。。)
import java.lang.Math;
public class prime_number{
public static void main(String[] args){
outer:
for(int i=2;i<=100;i++){
for(int j=2;j<=(int)Math.sqrt(i);j++)
{if(i%j==0) continue outer;
}
System.out.print(" "+i);
}
}
}
执行结果:
2 3 5 7 ….
这个地方可能有疑问:
i++为什么执行了,而后面的输出System.out.print(” “+i);为什么不执行,这是因为continue的作用,continue自动会执行下一次外层循环,所以i++还是会执行,除了这i++这个指令,其他都不会execute。
另外,参考另一篇博客的文章,详细介绍了这个标记的作用
outer1:
for(int i =0;i<4;i++){
System.out.println("begin to itrate. "+i);
for(int j =0;j<2;j++){
if(i==2){
continue outer1;
// break;
}
System.out.println("now the value of j is:"+j);
}
System.out.println("******************");
}
执行的结果是:
begin to itrate. 0
now the value of j is:0
now the value of j is:1
begin to itrate. 1
now the value of j is:0
now the value of j is:1
begin to itrate. 2
begin to itrate. 3
now the value of j is:0
now the value of j is:1
注:当i=2的时候,continue outer1 使程序回到了outer1最开始循环的位置,开始下一次循环,这个时候执行的循环是i=3而不是重新从i=0开始。同时当使用continue outer1跳出内层循环的时候,外层循环后面的语句也不会执行。也就是是在begin to itrate. 2后面不会出现一串*号了。
对比:
outer1:
for(int i =0;i<4;i++){
System.out.println("begin to itrate. "+i);
for(int j =0;j<2;j++){
if(i==2){
// continue outer1;
break;
}
System.out.println("now the value of j is:"+j);
}
System.out.println("******************");
}
注:我们直接使用break的话,只是直接跳出内层循环。结果其实就可以看出区别来:
begin to itrate. 0
now the value of j is:0
now the value of j is:1
begin to itrate. 1
now the value of j is:0
now the value of j is:1
begin to itrate. 2
begin to itrate. 3
now the value of j is:0
now the value of j is:1
—————————————————————–分割线
我们再来看看break+标签的效果
outer2:
for(int i =0;i<4;i++){
System.out.println("begin to itrate. "+i);
for(int j =0;j<2;j++){
if(i==2){
break outer2;
// break;
}
System.out.println("now the value of j is:"+j);
} System.out.println("******************");
}
结果:
begin to itrate. 0
now the value of j is:0
now the value of j is:1
begin to itrate. 1
now the value of j is:0
now the value of j is:1
begin to itrate. 2
注:从结果就可以看出当i=2的时候,break+标签 直接把内外层循环一起停掉了。而如果我们单独使用break的话就起不了这种效果,那样只是跳出内层循环而已。
最后说一句,Java中的标签只适合与嵌套循环中使用。