Documentation

The Java™ Tutorials
Hide TOC
Branching Statements分支语句
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements

Branching Statements分支语句

The break Statementbreak语句

The break statement has two forms: labeled and unlabeled.break语句有两种形式:标记和未标记。You saw the unlabeled form in the previous discussion of the switch statement.您在前面的switch语句讨论中看到了未标记的形式。You can also use an unlabeled break to terminate a for, while, or do-while loop, as shown in the following BreakDemo program:您还可以使用未标记的break来终止forwhiledo-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");
        }
    }
}

This program searches for the number 12 in an array.该程序在数组中搜索数字12。The break statement, shown in boldface, terminates the for loop when that value is found.粗体显示的break语句在找到该值时终止for循环。Control flow then transfers to the statement after the for loop.然后,控制流传输到for循环之后的语句。This program's output is:该程序的输出为:

Found 12 at index 4

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.未标记的break语句终止最内层的switchforwhiledo-while语句,但标记的break语句终止外部语句。The following program, BreakWithLabelDemo, is similar to the previous program, but uses nested for loops to search for a value in a two-dimensional array.以下程序BreakWithLabelDemo与上一个程序类似,但使用嵌套for循环搜索二维数组中的值。When the value is found, a labeled break terminates the outer for loop (labeled "search"):当找到该值时,一个带标签的断点终止外部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");
        }
    }
}

This is the output of the program.这是程序的输出。

Found 12 at 1, 0

The break statement terminates the labeled statement; it does not transfer the flow of control to the label.break语句终止带标签的语句;它不会将控制流传输到标签。Control flow is transferred to the statement immediately following the labeled (terminated) statement.控制流被传输到紧跟在标记(终止)语句之后的语句。

The continue Statementcontinue语句

The continue statement skips the current iteration of a for, while , or do-while loop.continue语句跳过forwhiledo-while循环的当前迭代。The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.未标记的表单跳到最内层循环体的末尾,并计算控制循环的boolean表达式。The following program, ContinueDemo , steps through a String, counting the occurrences of the letter "p".以下程序ContinueDemo逐步遍历一个String,计算字母“p”的出现次数。If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character.如果当前字符不是“p”,continue语句将跳过循环的其余部分并转到下一个字符。If it is a "p", the program increments the letter count.如果是“p”,程序将增加字母计数。

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

        String searchMe = "peter piper picked a " + "peck of pickled peppers";
        int max = searchMe.length();
        int numPs = 0;

        for (int i = 0; i < max; i++) {
            // interested only in p's
            if (searchMe.charAt(i) != 'p')
                continue;

            // process p's
            numPs++;
        }
        System.out.println("Found " + numPs + " p's in the string.");
    }
}

Here is the output of this program:以下是该程序的输出:

Found 9 p's in the string.

To see this effect more clearly, try removing the continue statement and recompiling.要更清楚地看到这种效果,请尝试删除continue语句并重新编译。When you run the program again, the count will be wrong, saying that it found 35 p's instead of 9.当您再次运行该程序时,计数将是错误的,表示它找到的是35个p,而不是9个p。

A labeled continue statement skips the current iteration of an outer loop marked with the given label.带标签的continue语句跳过用给定标签标记的外部循环的当前迭代。The following example program, ContinueWithLabelDemo, uses nested loops to search for a substring within another string.下面的示例程序ContinueWithLabelDemo使用嵌套循环在另一个字符串中搜索子字符串。Two nested loops are required: one to iterate over the substring and one to iterate over the string being searched.需要两个嵌套循环:一个迭代子字符串,另一个迭代正在搜索的字符串。The following program, ContinueWithLabelDemo, uses the labeled form of continue to skip an iteration in the outer loop.下面的程序ContinueWithLabelDemo使用continue的标记形式跳过外部循环中的迭代。

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

Here is the output from this program.这是这个程序的输出。

Found it

The return Statementreturn语句

The last of the branching statements is the return statement.最后一个分支语句是return语句。The return statement exits from the current method, and control flow returns to where the method was invoked.return语句从当前方法退出,控制流返回调用该方法的位置。The return statement has two forms: one that returns a value, and one that doesn't.return语句有两种形式:一种返回值,另一种不返回值。To return a value, simply put the value (or an expression that calculates the value) after the return keyword.要返回值,只需将值(或计算值的表达式)放在return关键字之后。

return ++count;

The data type of the returned value must match the type of the method's declared return value.返回值的数据类型必须与方法声明的返回值的类型匹配。When a method is declared void, use the form of return that doesn't return a value.当方法声明为void时,使用不返回值的返回形式。

return;

The Classes and Objects lesson will cover everything you need to know about writing methods.类和对象课程将涵盖您需要了解的有关编写方法的所有内容。


Previous page: The for Statement
Next page: Summary of Control Flow Statements