java的Break语句代码示例

Break语句有两种形式: 标记和未标记。您在前面关于 switch 语句的讨论中看到了未标记的表单。您还可以使用未标记的 break 来终止 for、 while 或 do-while 循环,如下面的 BreakDemo 程序所示:

class BreakDemo {
    public static void main(String[] args) {

        int[] arrayOfInts =
            { 32, 87, 3, 589,
              12, 1076, 2000,
              8, 622, 127 };
        int searchfor = 12;

        int i;
        boolean foundIt = false;

        for (i = 0; i < arrayOfInts.length; i++) {
            if (arrayOfInts[i] == searchfor) {
                foundIt = true;
                break;
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at index " + i);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

这个程序在一个数组中搜索数字12。Break 语句在找到 for 循环的值时终止该循环。然后,控制流在 for 循环之后传输到语句。这个程序的输出是:

Found 12 at index 4

未标记的 break 语句终止最里面的 switch for、 while 或 do-while 语句,但标记的 break 语句终止外部语句。下面的程序 BreakWithLabelDemo 与前面的程序类似,但是使用嵌套的 for 循环在二维数组中搜索值。当找到该值时,一个带标签的 break 将终止外部的 for 循环(标签为“ search”) :

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = {
            {  32,   87,    3, 589 },
            {  12, 1076, 2000,   8 },
            { 622,  127,   77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

这是程序的输出。

Found 12 at 1, 0

Break 语句终止带标签的语句; 它不将控制流转移到标签。控制流在标记的(终止的)语句之后立即传输到该语句。

java的Break语句代码示例

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注