[英]Break out of nested for loop without using break statement
我想脱离嵌套的for循环而不使用break
语句。 原因是在稍后使用break
语句时在程序中出现问题。
源代码是这样的:
for (int i = 0; i < 100; i++){
for (int j = 10; j < 100; j++) {
code;
if (code == true) {
:break out here:
}
}
}
那是goto语句不会很糟糕的少数情况之一。 更好的是,将循环提取到另一种方法中并使用return语句,如@SR SH所述。
尝试这样做,这很简单。
boolean flag = true;
for (int i = 0; i < 100; i++){
for (int j = 10; j < 100; j++) {
code;
if (code == true) {
j = 101; //any value that would make the condition check in for loop false
flag = false;
}
}
if (flag==false) {
i = 101; //any value that would make the condition check in for loop false
}
}
另一种可能性是使用布尔标志,该标志被添加到for循环的条件中。
boolean breakOut = false;
for (int i = 0; i < 100 && !breakOut; i++) {
for (int j = 10; j < 100 && !breakOut; j++) {
code;
if (code == true) {
breakOut = true;
}
}
}
for(int i = 0; i < 100; i++){
for (int j = 10; j < 100; j++) {
//code;
if(code == true){
j = 100; //will cancel the inner for loop.
}
}
}
根据要中断的循环,使i和/或j大于100
对此进行更改。
public void firstFor(int index){
for(int i =index; i<100;i++){
secondFor();
}
}
public void secondFor(){
for(int j=0;j<100;j++){
//your code...
if(code==true) return;
}
}
将您的代码块放在单独的方法中,然后使用return。 这将是最干净的方法。
您可以使用标签:
firstLabel: for (int i = 0; i < 100; i++) {
secondLabel: for (int j = 10; j < 100; j++) {
System.out.println("J = " + j);
if (j == 50) {
break firstLabel;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.