在 For 循环内的 If 语句内继续

Lei*_*yba 6 java android

我有一个 for 循环,其中我需要跳过一些行。

以更简单的方式,这就是我所做的:

for (int x = 0; x < 6; x++){
    if (x == 3) {
        continue;
    }
    Log.i("LOGLOG","LOGLOGLOG");
}
Run Code Online (Sandbox Code Playgroud)

continue 语句是否有效,就像跳转到 for 循环的另一个迭代一样?如果没有,最好的方法是什么?或者我该如何优化这个?

提前致谢。

Spi*_*idy 9

是的,继续会影响 for 循环。您将跳过当前循环块中的其余代码,并开始下一次迭代。

break 和 continue 不影响 if 语句,它们只影响循环(以及 switch 的中断)。

如果需要跳转多个循环,您甚至可以使用标签

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");
    }
}
Run Code Online (Sandbox Code Playgroud)