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

标签 java android

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

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

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

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

提前致谢。

最佳答案

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

breaks 和 continues 不影响 if 语句,它们只影响循环(和 break for switches)。

您甚至可以使用 labels如果你需要跳几个循环

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");
    }
}

关于java - 在 For 循环内的 If 语句内继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25800990/

相关文章:

java - 在java中重命名和删除文本文件

java - 如何在 Java 中运行不同的线程?

android - RecyclerView GridLayout Adapter - 如何居中项目

java - 安卓|获取文件 (.zip) 并保存

java - Java Android 中 Application 类和 Activity 之间传递数据

java - 网络请求超时或网络丢失或网络速度慢无法在 codenameone 中正确处理

java - 如何从 txt 文件中读取 Java 中的 2 个特定列?

android - 独立于 buildType 或 productFlavor 设置 resValue?

Android NFC App 不推送 Ndef 消息

android - 不将应用程序带到前台的警告框