java 在 For 循环中的 If 语句中继续
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25800990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Continue inside If statement inside For loop
提问by Lei Leyba
I have a for loop wherein I need to skip some lines.
我有一个 for 循环,我需要跳过一些行。
In a simpler way, here's what I did:
以更简单的方式,这就是我所做的:
for (int x = 0; x < 6; x++){
if (x == 3) {
continue;
}
Log.i("LOGLOG","LOGLOGLOG");
}
Will the continue statement work, as in jump to another iteration of the for loop, or not? If not, what is the best way to do this? Or how can I optimize this?
continue 语句是否会起作用,就像跳转到 for 循环的另一个迭代一样?如果不是,那么最好的方法是什么?或者我该如何优化?
Thanks in advance.
提前致谢。
采纳答案by Spidy
Yes the continue will affect the for loop. You will skip the rest of the code in the current loop block, and start the next iteration.
是的, continue 会影响 for 循环。您将跳过当前循环块中的其余代码,并开始下一次迭代。
breaks and continues do not affect if statements, they only affect loops (and breaks for switches).
break 和 continue 不影响 if 语句,它们只影响循环(和开关的中断)。
You can even use labelsif you need to jump several loops
如果您需要跳转多个循环,您甚至可以使用标签
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
回答by nilsmagnus
If you want to be explicit you can label your loop like this:
如果你想明确,你可以像这样标记你的循环:
myLoop : for (int x=0; x<6; x++){
if (x==3){
continue myLoop;
}
Log.i("LOGLOG","LOGLOGLOG");
}
This will also work for nested loops where you want to continue iterations on the outermost loop.
这也适用于您希望在最外层循环上继续迭代的嵌套循环。