Java 实例 - continue 关键字用法和标签(Label)

Java 实例 - continue 关键字用法和标签(Label)

Java 实例 - continue 关键字用法

Java continue 语句语句用来结束当前循环,并进入下一次循环,即仅仅这一次循环结束了,不是所有循环结束了,后边的循环依旧进行。

以下实例使用了 continue 关键字来跳过当前循环并开始下一次循环:

Main.java 文件

public class Main {

    public static void main(String[] args) {

        StringBuffer searchstr = new StringBuffer("hello how are you. ");

        int length = searchstr.length();

        int count = 0;

        for (int i = 0; i < length; i++) {

            if (searchstr.charAt(i) != 'h')

            continue;

            count++;

            searchstr.setCharAt(i, 'h');

        }

        System.out.println("发现 " + count

        + " 个 h 字符");

        System.out.println(searchstr);

    }

}

以上代码运行输出结果为:

发现 2 个 h 字符

hello how are you.

Java 实例 - 标签(Label)

Java 中的标签是为循环设计的,是为了在多重循环中方便的使用 break 和coutinue 。

以下实例当在循环中使用 break 或 continue 循环时跳到指定的标签处:

Main.java 文件

public class Main {

    public static void main(String[] args) {

        String strSearch = "This is the string in which you have to search for a substring.";

        String substring = "substring";

        boolean found = false;

        int max = strSearch.length() - substring.length();

        testlbl:

        for (int i = 0; i <= max; i++) {

            int length = substring.length();

            int j = i;

            int k = 0;

            while (length-- != 0) {

                if(strSearch.charAt(j++) != substring.charAt(k++)){

                    continue testlbl;

                }

            }

            found = true;

            break testlbl;

        }

        if (found) {

            System.out.println("发现子字符串。");

        }

        else {

            System.out.println("字符串中没有发现子字符串。");

        }

    }

}

以上代码运行输出结果为:

发现子字符串。

你可能感兴趣的:(java,开发语言)