顺序结构

程序从上到下逐行地执行,中间没有任何判断和跳转。

分支结构

根据条件,选择性地执行某段代码。
有if…else和switch两种分支语句。

    public class Test{
           public static void main(String args[]){
            String season = “summer”;
            switch (season) {
                   case “spring”:
                System.out.println(“春暖花开");
                break;
                   case “summer”:
                System.out.println(“夏日炎炎");
                break;
            case “autumn”:
                System.out.println(“秋高气爽");
                break;
            case “winter”:
                System.out.println(“冬雪皑皑");
                break;

                    default:
                System.out.println(“季节输入有误");
                break;
             }}}

switch 规则
switch(表达式)中表达式的返回值必须是下述几种类型之一:byte,short,char,int,枚举,String;
case子句中的值必须是常量,且所有case子句中的值应是不同的;
default子句是可任选的,当没有匹配的case时,执行default
break语句用来在执行完一个case分支后使程序跳出switch语句块;如果没有break,程序会顺序执行到switch结尾

if和switch的对比

如果判断的具体数值不多,而且符合byte、 short 、int、 char这四种类型。虽然两个语句都可以使用,建议使用swtich语句。因为效率稍高。

其他情况:对区间判断,对结果为boolean类型判断,使用if,if的使用范围更广。

循环结构

根据循环条件,重复性的执行某段代码。
有while、do…while、for三种循环语句。
注:JDK1.5之后提供了foreach循环,方便的遍历集合、数组元素。
for循环
for (初始化表达式①; 布尔值测试表达式②; 更改表达式){
语句或语句块③;

while循环
语法格式
[初始化语句]
while( 布尔值测试表达式){
语句或语句块;
[更改语句;]
}

    public class WhileLoop {
                public static void main(String args[]){
                int result = 0;
            int i=1;
            while(i<=100) {
                    result += i;
                                   i++;
            }
                    System.out.println("result=" + result);
                 }
        } 

do-while
语法格式
[初始化语句]
do{
语句或语句块;
[更改语句;]
}while(布尔值测试表达式);

public class WhileLoop {
                public static void main(String args[]){
                  int result = 0,  i=1;
                    do{
                           result += i;
                                 i++;
                 }while(i<=100);
             System.out.println("result=" + result);
               }
        }  

特殊流程控制语句 return

return:并非专门用于结束循环的,它的功能是结束一个方法。当一个方法执行到一个return语句时,这个方法将被结束。

与break和continue不同的是,return直接结束整个方法,不管这个return处于多少层循环之内

** 注意事项**
break只能用于switch语句和循环语句中。
continue 只能用于循环语句中。
二者功能类似,但continue是终止本次循环,break是终止本层循环。
break、continue之后不能有其他的语句,因为程序永远不会执行其后的语句。