Java - Language Basics - Control Flow Statements

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/flow.html

Language Basics

Control Flow Statements

源文件中的语句通常按照出现的顺序从上到下执行。然而,控制流语句通过使用决策制定、循环和分支来分解执行流,使您的程序能够有条件地执行特定的代码块。本节描述Java编程语言支持的决策语句(if-then、if-then-else、switch)、循环语句(for、while、do-while)和分支语句(break、continue、return)。

The if-then and if-then-else Statements

The if-then Statement

//if-then 示例
void applyBrakes() {
    // the "if" clause: bicycle must be moving
    if (isMoving){ 
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}

//当“then”只有一个语句时,大括号可写可不写
void applyBrakes() {
    // same as above, but without braces 
    if (isMoving)
        currentSpeed--;
}

The if-then-else Statement

没啥好说

The switch Statement

与if-then和if-then-else语句不同,switch语句可以有多个可能的执行路径。switch处理byte、short、char和int等基本数据类型。它还适用于枚举类型(在Enum类型中讨论)、String类和一些包装某些基本类型的特殊类:Character、Byte、Short和Integer(在数字和字符串中讨论)。

switch Statement示例
public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}

switch语句的主体称为switch块。switch块里面可有一个或者多个case。switch语句计算其表达式,然后执行匹配的case标号之后的所有语句。

你也可以用if-then-else Statement 代替 switch Statement。

决定是使用if-then-else语句还是switch语句取决于可读性和语句测试的表达式。if-then-else语句可以基于值或条件的范围测试表达式,而switch语句仅基于单个整数、枚举值或String对象测试表达式。

在switch语句中,break语句时必须的,break语句用于终止并且闭合switch语句;如果没有break语句,switch语句将失效。

成功匹配case之后,case之后的语句会被执行,一直到遇到break语句后结束。参考SwitchDemoFallThrough:

public class SwitchDemoFallThrough {

    public static void main(String[] args) {
        java.util.ArrayList<String> futureMonths =
            new java.util.ArrayList<String>();

        int month = 8;

        switch (month) {
            case 1:  futureMonths.add("January");
            case 2:  futureMonths.add("February");
            case 3:  futureMonths.add("March");
            case 4:  futureMonths.add("April");
            case 5:  futureMonths.add("May");
            case 6:  futureMonths.add("June");
            case 7:  futureMonths.add("July");
            case 8:  futureMonths.add("August");
            case 9:  futureMonths.add("September");
            case 10: futureMonths.add("October");
            case 11: futureMonths.add("November");
            case 12: futureMonths.add("December");
                     break;
            default: break;
        }

        if (futureMonths.isEmpty()) {
            System.out.println("Invalid month number");
        } else {
            for (String monthName : futureMonths) {
               System.out.println(monthName);
            }
        }
    }
}

This is the output from the code:

August
September
October
November
December

从技术上来说,最后一个break是不需要的,因为在执行倒数第二个break之后已经跳出了switch。default部分通常用来处理列举的case之外的情况。

下面的代码示例SwitchDemo2展示了一个语句如何具有多个case标号:

多个case标号
class SwitchDemo2 {
    public static void main(String[] args) {

        int month = 2;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case 1: case 3: case 5:
            case 7: case 8: case 10:
            case 12:
                numDays = 31;
                break;
            case 4: case 6:
            case 9: case 11:
                numDays = 30;
                break;
            case 2:
                if (((year % 4 == 0) &&
                     !(year % 100 == 0))
                     || (year % 400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break;
        }
        System.out.println("Number of Days = "
                           + numDays);
    }
}

Using Strings in switch Statements

在Java SE 7和更高版本中,可以在switch语句的表达式中使用String对象。下面的代码示例StringSwitchDemo根据名为month的字符串的值显示月份编号:

Strings in switch Statements
public class StringSwitchDemo {

    public static int getMonthNumber(String month) {

        int monthNumber = 0;

        if (month == null) {
            return monthNumber;
        }

        switch (month.toLowerCase()) {
            case "january":
                monthNumber = 1;
                break;
            case "february":
                monthNumber = 2;
                break;
            case "march":
                monthNumber = 3;
                break;
            case "april":
                monthNumber = 4;
                break;
            case "may":
                monthNumber = 5;
                break;
            case "june":
                monthNumber = 6;
                break;
            case "july":
                monthNumber = 7;
                break;
            case "august":
                monthNumber = 8;
                break;
            case "september":
                monthNumber = 9;
                break;
            case "october":
                monthNumber = 10;
                break;
            case "november":
                monthNumber = 11;
                break;
            case "december":
                monthNumber = 12;
                break;
            default: 
                monthNumber = 0;
                break;
        }

        return monthNumber;
    }

    public static void main(String[] args) {

        String month = "August";

        int returnedMonthNumber =
            StringSwitchDemo.getMonthNumber(month);

        if (returnedMonthNumber == 0) {
            System.out.println("Invalid month");
        } else {
            System.out.println(returnedMonthNumber);
        }
    }
}

在比较的时候用的是String.equals方法。
有检查为null和大小写转换的操作。

The while and do-while Statements

while语句在特定条件为真时继续执行语句块。其语法可以表示为:

while (expression) {
     statement(s)
}

while语句计算表达式,它必须返回一个布尔值。如果表达式的计算结果为true,则while语句执行while块中的语句。while语句继续测试表达式并执行它的块,直到表达式的计算结果为false。使用while语句打印从1到10的值可以像下面的while demo程序那样完成:

class WhileDemo {
    public static void main(String[] args){
        int count = 1;
        while (count < 11) {
            System.out.println("Count is: " + count);
            count++;
        }
    }
}

你可以使用while语句实现无限循环,如下所示:

while (true){
    // your code goes here
}

Java编程语言还提供了do-while语句,它可以表示为:

do {
     statement(s)
} while (expression);

do-while和while的区别在于do-while在循环的底部而不是顶部计算其表达式。因此,do块中的语句总是至少执行一次。

The for Statement

for语句提供了一种紧凑的方法来迭代一段范围内的值。程序员经常将其称为“for循环”,因为它会重复循环,直到满足特定的条件。for语句的一般形式可以表示为:

for (initialization; termination;
     increment) {
    statement(s)
}

当使用这个版本的for语句时,请记住:

  • 初始化表达式(initialization)初始化循环;它在循环开始时执行一次。
  • 当终止表达式(termination)的计算结果为false时,循环终止。
  • 递增表达式(increment)在循环的每次迭代之后被调用;对于这个表达式,增加和减少都是可以的。

下面的程序,ForDemo,使用一般形式的for语句打印数字1到10到标准输出:

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}

注意代码是如何在初始化表达式中声明变量的,例如上面的例子中的int i = 1,它的作用域是从它初始化开始~所处的for语句结束,所以在ermination and increment expressions中也有效。

如果控制for语句的变量在循环之外不需要(例如上面例子的 int i=1,i如果只在for语句中使用),最好在初始化表达式(initialization)中声明该变量。名称i, j和k通常用于控制循环;在初始化表达式中声明它们将限制它们的生命周期并减少错误。

for循环的三个表达式是可选的;可以按照如下方式创建一个无限循环:

// infinite loop 无限循环 通常结合break使用
for ( ; ; ) {

    // your code goes here
}

for语句还有另一种设计用于遍历集合和数组的形式。这种形式有时被称为增强的for语句,可用于使循环更紧凑、更易于阅读。为了进行演示,考虑下面的数组,它保存了数字1到10:

int[] numbers = {1,2,3,4,5,6,7,8,9,10};

下面的程序EnhancedForDemo使用了增强的for循环遍历数组:


class EnhancedForDemo {
    public static void main(String[] args){
         int[] numbers =
             {1,2,3,4,5,6,7,8,9,10};
         for (int item : numbers) {
             System.out.println("Count is: " + item);
         }
    }
}

输出结果:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10

建议尽可能使用这种形式的for语句,而不是一般形式(为什么?)。

Branching(分支) Statements

The break Statement

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

使用break结束for循环
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语句根据标记终止外部语句:

break配合标记使用示例
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*/
break语句终止带标签的语句;它不会将控制流转移到标签。控制流被转移到紧跟在标记(终止)语句之后的语句。(也就是将break Search之后将执行 if (foundIt) 语句)

The continue Statement

直接看例子吧。

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.
*/

如果当前字符不是p,则continue语句跳过循环的其余部分,继续执行下一个字符。如果是"p",程序将增加字母计数。'

contiue也可以配合标记使用

contiue配合标记使用示例
/*
判定字符串包含其他字符串
判定方法:
L和s比较,不一样,进入下一次for循环
o和s比较,不一样,进入下一次for循环
o和s比较,不一样,进入下一次for循环
k和s比较,不一样,进入下一次for循环
...
直到s和s比较,一样 ——> u和u比较,一样 ——> b和b比较,一样 ——> foundIt = true,退出循环

*/

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 Statement

最后一个分支语句是返回语句(return Statement)。return语句从当前方法中退出,控制流返回到调用方法的位置。return语句有两种形式:一种返回值,另一种不返回值。要返回值,只需将值(或计算值的表达式)放在return关键字之后。

return ++count;

返回值的数据类型必须与方法声明的返回值的类型匹配。当一个方法被声明为void时,使用不返回值的return形式。

return;

Summary of Control Flow Statements

if-then语句是所有控制流语句中最基本的。它告诉您的程序,只有当某个测试的结果为true时,才执行代码的某个部分。当“if”子句的计算结果为false时,if-then-else语句提供了一个次要的执行路径。与if-then和if-then-else不同,switch语句允许任意数量的可能执行路径。while和do-while语句在特定条件为真时持续执行语句块。do-while和while的区别在于do-while在循环的底部而不是顶部计算其表达式。因此,do块中的语句总是至少执行一次。for语句提供了一种紧凑的方法来迭代一段范围内的值。它有两种形式,其中一种设计用于遍历集合和数组。

posted @ 2022-05-13 11:53  Pril  阅读(54)  评论(0)    收藏  举报