Java基础教程(9)--流程控制

一.分支结构

1.if语句

  if语句会与其后的第一条语句或代码块结合,且只有当判断条件为true时才执行语句或代码块。例如,自行车只有在运动的时候才可以减速,就像下面这样:

void applyBrakes() {
    if (isMoving){ 
        currentSpeed--;
    }
}

  如果判断条件为false,也就是自行车处于静止状态时,将会跳过if语句后面的语句或代码块。
  如果if语句后只有一条需要执行的语句,既可以使用大括号,也可以不使用。不过按照惯例来说,任何时候都应该使用大括号,这样可以避免有时因为忘记大括号而带来的一些逻辑错误。for、while语句也是同理。

2.if-else语句

  if语句只是指出了当判断条件为true时需要执行的语句。使用if-else语句可以同时指定当判断条件为true和false时应该执行的语句。当自行车没有处于运动状态时,可以简单地输出一条信息:

void applyBrakes() {
    if (isMoving){ 
        currentSpeed--;
    } else {
        System.out.println("The bicycle has already stopped!");
    }
}

  下面的程序根据分数来给出对应的等级:

class IfElseDemo {
    public static void main(String[] args) {
        int testscore = 76;
        char grade;
        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}

  该程序最终的输出为:

Grade = C

  虽然testscore满足很多条件,例如76>=70和76>=60等,但是,一旦满足了一个条件,就会执行对应的语句(grade = 'C';)并跳过剩余条件。

3.switch语句

  与if和if-else语句不同,switch语句可以有许多可能的执行路径。例如下面的代码将会使用switch语句根据month的值来输出对应的月份:

public class SwitchDemo1 {
    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);
    }
}

  该程序将会输出:

August

  switch语句的判断条件是一个变量或表达式,它的类型可以是byte,short,char和int以及它们的包装类(Character,Byte,Short,和Integer),还可以是字符串和枚举类型,case后面是这些类型的字面量。
  default语句用来处理当所有case标签都不满足的情况。break语句用来退出switch块。如果一个case语句最后没有使用break,将会执行下一个case的语句而不进行判断,直到遇到break或switch块结束。下面的例子根据month的值来输出季节:

public class SwitchDemo2 {
    public static void main(String[] args) {
        int month = 5;
        switch(month) {
            case 2:
            case 3:
            case 4: System.out.println("Spring");
            case 5:
            case 6:
            case 7: System.out.println("Summer");
            case 8:
            case 9:
            case 10: System.out.println("Autumn");
            case 11:
            case 12:
            case 1: System.out.println("Winter");
        }
    }
}

  该程序将会输出:

Summer

  其实无论month的值是5,6还是7,都会输出Summer,因为case 5和case 6都没有break语句,即使匹配到了它们,程序也还是会进入case 7。

二.循环结构

1.while语句和do-while语句

  当判断条件为true时,while语句将会重复执行代码块中的内容,直到判断条件为false。它的语法如下:

while (expression) {
     statement(s)
}

  下面的程序使用while循环打印出1~10:

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循环打印出1~10:

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

2.for循环

  for循环可以控制循环的次数,它的的语法如下:

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

  使用for循环时,需要注意:

  • initialization通常用来更初始化计数器,它只在循环开始前执行一次。
  • condition时每一次循环前要判断的条件,一旦条件不满足,循环将结束。
  • increment用来对计数器进行更新,它在每次循环结束后执行。

  下面的程序使用for循环打印出1~10:

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

  注意变量i的声明位置。由于它是在初始化表达式中声明的,因此它的范围和生存周期仅在循环内有效。一旦循环结束,变量i将无法访问。
  for循环的三个表达式都是可选的,任意一个都可以为空。下面的语句将会创建一个无限循环:

for ( ; ; ) {
    // your code goes here
}

  for循环还有一种用于迭代数组和集合的格式,称为增强型for循环。下面的程序使用增强型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);
         }
    }
}

三.中断控制流

1.break

  break语句用于结束当前控制结构,它有两种形式,带标签的break语句和不带标签的break语句。在之前的switch样例中已经见到了不带标签的break语句。还可以使用不带标签的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");
        }
    }
}

  该程序的输出是:

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

  当找到12时,程序将跳出search对应的for循环。该程序的输出是:

Found 12 at 1, 0

2.continue

  continue跳到循环体的末尾,并执行循环条件的判断。下面的程序统计字母p的出现次数。如果当前字符不是p,则continue语句将跳过循环的其余部分并继续执行下一次循环。如果是 “p”,计数器会加1:

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++) {
            if (searchMe.charAt(i) != 'p')
                continue;
            numPs++;
        }
        System.out.println("Found " + numPs + " p in the string.");
    }
}

  该程序的输出是:

Found 9 p in the string.

  和break一样,continue也分为带标签的continue语句和不带标签的continue语句。带标签的continue语句将会结束当前的循环并开始下一次标签对应的循环。下面的程序使用带标签的continue和break语句来判断一个字符串是否包含另一个字符串:

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

  该程序的输出是:

Found it

3.return

  最后一个可以中断控制流的语句是return语句,它可以从当前的方法中退出。return语句有两种形式,使用返回值和不使用返回值。如果要返回一个值,只需要将值或表达式放在return关键字后面。例如:

return ++count;

  返回值的数据类型必须与方法声明的返回值的类型匹配。使用没有返回值的return语句时,方法的返回值类型必须声明为void,例如:

return;
posted @ 2018-10-15 22:17  maconn  阅读(464)  评论(0编辑  收藏  举报