1.break与continue
源码:
public static void main(String[] args)
{
for(int i=0;i<10;i++)
{
if(i==3)
continue;
if(i==8)
break;
System.out.println("i="+i);
}
} 输出:
i=0
i=1
i=2
i=4
i=5
i=6
i=7
2.带标签的continue与break
在 Java 里唯一需要用到标签的地方就是拥有嵌套循环,而且想中断或继续多个嵌套级别的时候。
①在for循环中 源码:
public static void main(String[] args)
{
outer:
for (int i = 0; i < 10; i++)
{
inner:
for (int j = 0; j < 10; j++)
{
if (j == 1)
{
//equals continue
continue inner; //only not print when j=1
}
if (j == 3)
{
continue outer; //only not print since j>=3
}
if (i == 4)
{
//equals break
break inner; //only stop inner loop when i=4
}
if(i==6)
{
break outer; //stop both loop since i=6
//if you want to return something when stop all loop, then use return.
}
System.out.println("i=" + i + ",j=" + j);
}
}
} 输出:
i=0,j=0
i=0,j=2
i=1,j=0
i=1,j=2
i=2,j=0
i=2,j=2
i=3,j=0
i=3,j=2
i=5,j=0
i=5,j=2
②在while循环中
源码:
public static void main(String[] args)
{
int i = 0;
outer:
while (i<10)
{
int j = 0;
inner:
while (j<10)
{
j++;
if(j==1)
//equals continue
continue inner;//only not print when j=1;
if(j==4)
break inner; // only stop inner loop when j=4
if(i==4)
break inner; //only stop inner loop when i=4
if(i==6)
break outer; //stop both loops when i=6
System.out.println("i=" + i + ",j=" + j);
}
i++;
}
} 输出:
i=0,j=2
i=0,j=3
i=1,j=2
i=1,j=3
i=2,j=2
i=2,j=3
i=3,j=2
i=3,j=3
i=5,j=2
i=5,j=3