4 ways out of Java for loop multilayer
First, use the keyword return control
for (int i = 0;i<10;i++){
for (int j = 0; j<10; j++)
{
if (i<10){
System.out.println("retuen 跳出循环");
return;
}
}
}
//使用return将退出方法的作用域,栈空间释放,跳出最外层循环是必然的!
Second, the definition of a Boolean control
boolean a=true;
boolean b=true;
for (int i = 0;i<10 && a;i++){
for (int j = 0; j<10 && a; j++)
{
if (i<10){
System.out.println("定义布尔值 跳出循环");
a=flase;
//b=flase;(根据需要把b添加在循环条件中!)
}
}
}
//达到满足的条件后,将布尔值置为flase;内外循环的条件都不成立,循环无法进行!
Third, the definition of an identifier configured to control the break keyword
outCycle:for (int i= 0 ;i<10;i++){
innerCycel:
for (int j=0; j<10; j++){
if (j == i){
System.out.println("定义标识符 跳出循环");
break outCycle;
}
}
}
//相当于给外层循环叫一个名字,达到条件后配合break跳出整个循环!
The use of an exception to terminate the loop
try{
for (int i = 0;i<10;i++){
for (int j = 0; j<10; j++)
{
if (i<10){
System.out.println("使用异常 跳出循环");
throw new Exception();
}
}
}
}catch (Exception e) {
....
}
//发生异常,循环就直接终止了!
V. Summary
break : out of the current cycle, the single-cycle is simple, you can use the break statement!
continue : out of this cycle, continue to the next cycle, that is, this cycle continue following statement is not executed.
Summary : flexible use depending on conditions! There may be other methods, refer to!