我有一个这样的嵌套循环构造:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break; // Breaks out of the inner loop
}
}
}
现在我怎样才能打破这两个循环?我已经研究过类似的问题,但没有一个与Java相关。我无法应用这些解决方案,因为大多数人都使用goto。
我不想将内部循环放在不同的方法中。
我不想返回循环。当中断时,我完成了循环块的执行。
for(int j=0;j<5;j++)//内部循环应替换为对于(int j=0;j<5&&!exitloops;j++)。
这里,在这种情况下,如果条件为True,则应退出完整的嵌套循环。但如果我们只对上循环使用exitloops
for (int i = 0; i < 5 && !exitloops; i++) //upper loop
然后,内部循环将继续,因为并没有额外的标志通知此内部循环退出。
示例:如果i=3和j=2,则条件为假。但在下一次内循环迭代中,j=3,则条件(i*j)变为9,这是真的,但内循环将继续,直到j变为5。
因此,它也必须对内部循环使用exitloops。
boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true.
for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement.
if (i * j > 6) {
exitloops = true;
System.out.println("Inner loop still Continues For i * j is => "+i*j);
break;
}
System.out.println(i*j);
}
}
for(int j=0;j<5;j++)//内部循环应替换为对于(int j=0;j<5&&!exitloops;j++)。
这里,在这种情况下,如果条件为True,则应退出完整的嵌套循环。但如果我们只对上循环使用exitloops
for (int i = 0; i < 5 && !exitloops; i++) //upper loop
然后,内部循环将继续,因为并没有额外的标志通知此内部循环退出。
示例:如果i=3和j=2,则条件为假。但在下一次内循环迭代中,j=3,则条件(i*j)变为9,这是真的,但内循环将继续,直到j变为5。
因此,它也必须对内部循环使用exitloops。
boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true.
for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement.
if (i * j > 6) {
exitloops = true;
System.out.println("Inner loop still Continues For i * j is => "+i*j);
break;
}
System.out.println(i*j);
}
}
如果是新的实现,可以尝试将逻辑重写为If-else_If-else语句。
while(keep_going) {
if(keep_going && condition_one_holds) {
// Code
}
if(keep_going && condition_two_holds) {
// Code
}
if(keep_going && condition_three_holds) {
// Code
}
if(keep_going && something_goes_really_bad) {
keep_going=false;
}
if(keep_going && condition_four_holds) {
// Code
}
if(keep_going && condition_five_holds) {
// Code
}
}
否则,当发生特殊情况时,您可以尝试设置一个标志,并在每个循环条件中检查该标志。
something_bad_has_happened = false;
while(something is true && !something_bad_has_happened){
// Code, things happen
while(something else && !something_bad_has_happened){
// Lots of code, things happens
if(something happened){
-> Then control should be returned ->
something_bad_has_happened=true;
continue;
}
}
if(something_bad_has_happened) { // The things below will not be executed
continue;
}
// Other things may happen here as well, but they will not be executed
// once control is returned from the inner cycle.
}
在这里!因此,虽然简单的中断不起作用,但可以使用continue继续工作。
如果您只是简单地将逻辑从一种编程语言移植到Java,并且只想让它正常工作,那么可以尝试使用标签。