当前位置: 移动技术网 > IT编程>开发语言>Java > Java基础教程(9)--流程控制

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

2018年10月16日  | 移动技术网IT编程  | 我要评论

一.分支结构

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;

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网