Java中的流程控制

Java中的流程控制

1.流程控制概述

​ 在一个程序执行的过程中,各条语句的执行顺序对程序的结果是有直接影响的。也就是说,程序的流程对运行结果 有直接的影响。所以,我们必须清楚每条语句的执行流程。而且,很多时候我们要通过控制语句的执行顺序来实现 我们要完成的功能。

2.顺序结构

  • 按照程序的书写顺序来正常输出

    public class Demo01Sequence {
    	public static void main(String[] args) {
    		System.out.println("今天天气不错");
    		System.out.println("挺风和日丽的");
    		System.out.println("我们下午没课");
    		System.out.println("这的确挺爽的");
    	}
    }
    

3.判断语句

  • 判断语句if

    public class Demo02If {
    	public static void main(String[] args) {
    		System.out.println("今天天气不错,正在压马路……突然发现一个快乐的地方:网吧");
    		int age = 19;
    		if (age >= 18) {
    			System.out.println("进入网吧,开始high!");
    			System.out.println("遇到了一群猪队友,开始骂街。");
    			System.out.println("感觉不爽,结账走人。");
    		}
    		System.out.println("回家吃饭");
    	}
    }
    
  • 判断语句if - else

    • 标准的if - else 语句 ----- 来判断奇数偶数

      public class Demo03IfElse {
      	public static void main(String[] args) {
      		int num = 666;
      		if (num % 2 == 0) { // 如果除以2能够余数为0,说明是偶数
      			System.out.println("偶数");
      		} else {
      			System.out.println("奇数");
      		}
      	}
      }
      
  • 判断语句 if…else if…else

    • 先判断,再进入符合的代码段执行

    • 例题 : 若 : x和y的关系满足如下:如果x >= 3,那么y = 2x + 1; 如果-1 < x < 3,那么y = 2x; 如果x <= -1,那么y = 2x – 1;

      ublic class Demo04IfElseExt {
      	public static void main(String[] args) {
      		int x = -10;
      		int y;
      		if (x >= 3) {
      			y = 2 * x + 1;
      		} else if (-1 < x && x < 3) {
      			y = 2 * x;
      		} else {
      			y = 2 * x - 1;
      		}
      		System.out.println("结果是:" + y);
      	}
      }
      
  • 语句练习

    • 输入学生成绩,给学生成绩风挡输出. 示例 : 输入 成绩 90 输出 “优秀”

      public class IfElsePractise {
          public static void main(String[] args) {
              System.out.println("请输入学生成绩" );
              int nextInt = new Scanner(System.in).nextInt();
              getScore(nextInt);
          }
      
          public static void getScore(int nextInt) {
              if(nextInt >= 90 && nextInt < 100){
                  System.out.println("该学生的成绩为" + nextInt+ "优秀" );
              }else if (nextInt < 90 && nextInt >=80){
                  System.out.println("该学生的成绩为" + nextInt+ "良好" );
              }else if (nextInt < 80 && nextInt >=60){
                  System.out.println("该学生的成绩为" + nextInt+ "及格" );
              }else if (nextInt < 60 && nextInt >=0){
                  System.out.println("该学生的成绩为" + nextInt+ "不及格" );
              }else {
                  System.out.println("该学生的成绩为" + nextInt+ "成绩输入无效,请重新输入" );
              }
          }
      }
      
  • if 语句和三元运算符分互换

    • 题目描述:使用三元运算符和标准的if-else语句分别实现:取两个数字当中的最大值

      public class Demo06Max {
      	public static void main(String[] args) {
      		int a = 105;
      		int b = 20;
      		
      		// 首先使用三元运算符
      		// int max = a > b ? a : b;
      		
      		// 使用今天的if语句
      		int max;
      		if (a > b) {
      			max = a;
      		} else {
      			max = b;
      		}
      		
      		System.out.println("最大值:" + max);
      	}
      }
      

4.选择语句

  • ​ 选择语句 – switch

    • switch语句格式:

    • 使用switch语句的注意事项

      • 多个case后面的数值不可以重复。
      • switch后面小括号当中只能是下列数据类型:
        1. 基本数据类型:byte/short/char/int
        2. 引用数据类型:String字符串、enum枚举
      • switch语句格式可以很灵活:前后顺序可以颠倒,而且break语句还可以省略。
        “匹配哪一个case就从哪一个位置向下执行,直到遇到了break或者整体结束为止。” =====> 这也是case穿透的原因.
    • 执行流程

      • 首先计算出表达式的值
      • 其次,和case依次比较,一旦有对应的值,就会执行相应的语句,在执行的过程中,遇到break就会结 束
      • 最后,如果所有的case都和表达式的值不匹配,就会执行default语句体部分,然后程序结束掉。
    • switch语句中,表达式的数据类型,可以是byte,short,int,char,enum(枚举),JDK7后可以接收字符串。

    • 代码展示:

      public static void main(String[] args) {
      		int num = 10;
      		
      		switch (num) {
      			case 1:
      				System.out.println("星期一");
      				break;
      			case 2:
      				System.out.println("星期二");
      				break;
      			case 3:
      				System.out.println("星期三");
      				break;
      			case 4:
      				System.out.println("星期四");
      				break;
      			case 5:
      				System.out.println("星期五");
      				break;
      			case 6:
      				System.out.println("星期六");
      				break;
      			case 7:
      				System.out.println("星期日");
      				break;
      			default:
      				System.out.println("数据不合理");
      				break; // 最后一个break语句可以省略,但是强烈推荐不要省略
      		}
      	}
      }
      
  • case的穿透性

  • “匹配哪一个case就从哪一个位置向下执行,直到遇到了break或者整体结束为止。”

    下面代码 :case 2 后面的break 被注释掉了,就会从这向下执行.直到遇到第3个case的break截至.

    • public class Demo08SwitchNotice {
      	public static void main(String[] args) {
      		int num = 2;
      		switch (num) {
      			case 1:
      				System.out.println("你好");
      				break;
      			case 2:
      				System.out.println("我好");
      				// break;
      			case 3:
      				System.out.println("大家好");
      				break;
      			default:
      				System.out.println("他好,我也好。");
      				break;
      		} // switch
      	}
      }
      

      输出结果

      ​ [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0GVhvYVi-1596457032351)(C:\Users\tiancy\AppData\Roaming\Typora\typora-user-images\image-20200803180344870.png)]

5.循环语句

  • ​ 循环概述

    • 循环语句可以在满足循环条件的情况下,反复执行某一段代码,这段被重复执行的代码被称为循环体语句,当反复 执行这个循环体时,需要在合适的时候把循环判断条件修改为false,从而结束循环,否则循环将一直执行下去,形成死循环。
  • 循环语句 for

    • for 循环格式 :

      for(初始化表达式①; 布尔表达式②; 步进表达式④){ 循环体③ }
      
    • 执行流程

      • 执行顺序:①②③④>②③④>②③④…②不满足为止。
      • ①初始化语句:在循环开始最初执行,而且只做唯一一次。
      • ②条件判断:如果成立,则循环继续;如果不成立,则循环退出。
      • ③循环体:重复要做的事情内容,若干行语句。
      • ④步进语句:每次循环之后都要进行的扫尾工作,每次循环结束之后都要执行一次。
    • 代码演示: 计算 1 - 100 之间的偶数和

      public class OldSum {
          public static void main(String[] args) {
              int sum = 0;
              for (int i = 0; i <= 100; i++) {
                  if(i % 2 == 0){
                      sum += i;
                  }
              }
              System.out.println(sum);
          }
      }
      
  • 循环语句 while

    • while循环语句标准格式:

      初始化表达式① 
      while(布尔表达式②){
      	循环体③ 
      	步进表达式④ 
      	}
      
    • while循环语句拓展格式:

      初始化语句;
      while (条件判断) {
      	循环体;
      	步进语句;
      }
      
    • 执行流程

      • 执行顺序:①②③④>②③④>②③④…②不满足为止。

        ①负责完成循环变量初始化。

        ②负责判断是否满足循环条件,不满足则跳出循环。

        ③具体执行的语句。

        ④循环后,循环变量的变化情况。

    • 代码展示

      public class Demo10While {
      	public static void main(String[] args) {
      		for (int i = 1; i <= 10; i++) {
      			System.out.println("我错啦!" + i);
      		}
      		System.out.println("=================");
      		
      		int i = 1; // 1. 初始化语句
      		while (i <= 10) { // 2. 条件判断
      			System.out.println("我错啦!" + i); // 3. 循环体
      			i++; // 4. 步进语句
      		}
      	}
      }
      
  • 循环语句 do … while

    • 格式

      初始化表达式①
      	do{ 
              循环体③ 
              步进表达式④ 
      	}while(布尔表达式②);
      
    • 执行流程

      执行顺序:①③④>②③④>②③④…②不满足为止。

      ①负责完成循环变量初始化。

      ②负责判断是否满足循环条件,不满足则跳出循环。

      ③具体执行的语句

      ④循环后,循环变量的变化情况

    • 代码展示

      public class Demo11DoWhile {
      	public static void main(String[] args) {
      		for (int i = 1; i <= 10; i++) {
      			System.out.println("原谅你啦!起来吧!地上怪凉!" + i);
      		}
      		System.out.println("===============");
      		
      		int i = 1; // 1. 初始化语句
      		do {
      			System.out.println("原谅你啦!起来吧!地上怪凉!" + i); // 3. 循环体
      			i++; // 4. 步进语句
      		} while (i <= 10); // 2. 条件判断
      	}
      }
      
    • do…while循环的特点:

      • 无条件执行一次循环体,即使我们将循环条件直接写成false,也依然会循环一次。这样的循环具有一定的风险性,因此初学者不建议使用do…while循环。
  • 循环语句的区别

    • for 和 while 的小区别:

      • 如果条件判断从来没有满足过,那么for循环和while循环将会执行0次,但是do-while循环会执行至少一次。

      • for循环的变量在小括号当中定义,只有循环内部才可以使用。while循环和do-while循环初始化语句本来就在外面.所以出来循环之后还可以继续使用。

      • 代码

        public class Demo13LoopDifference {
        	public static void main(String[] args) {
        		for (int i = 1; i < 0; i++) {
        			System.out.println("Hello");
        		}
        		// System.out.println(i); // 这一行是错误写法!因为变量i定义在for循环小括号内,只有for循环自己才能用。
        		System.out.println("================");
        		
        		int i = 1;
        		do {
        			System.out.println("World");
        			i++;
        		} while (i < 0);
        		// 现在已经超出了do-while循环的范围,我们仍然可以使用变量i
        		System.out.println(i); // 2
        	}
        }
        
      • 控制条件语句所控制的那个变量,在for循环结束后,就不能再被访问到了.

      • 而while循环结束还可以继使用,如果你想继续使用,就用while,否则推荐使用for。原因是for循环结束,该变量就从内存中消 失,能够提高内存的使用效率

  • 跳出语句

    1. break关键字

      • 大体上将 :可以终止switch或者循环

      • 可以用在switch语句当中,一旦执行,整个switch语句立刻结束。

      • 还可以用在循环语句当中,一旦执行,整个循环语句立刻结束。打断循环。

      • 在已知循环次数的时候使用推荐使用for,循环次数未知的时推荐使用while。

        在选择结构switch语句中

        在循环语句中

        离开使用场景的存在是没有意义的

        public class Demo14Break {
        	public static void main(String[] args) {
        		for (int i = 1; i <= 10; i++) {
        			// 如果希望从第4次开始,后续全都不要了,就要打断循环
        			if (i == 4) { // 如果当前是第4次
        				break; // 那么就打断整个循环
        			}
        			System.out.println("Hello" + i);
        		}
        	}
        }
        
    2. continue

      • 另一种循环控制语句是continue关键字。一旦执行,立刻跳过当前次循环剩余内容,马上开始下一次循环。

      • public class Demo15Continue {
        	public static void main(String[] args) {
        		for (int i = 1; i <= 10; i++) {
        			if (i == 4) { // 如果当前是第4层
        				continue; // 那么跳过当前次循环,马上开始下一次(第5层)
        			}
        			System.out.println(i + "层到了。");
        		}
        	}
        }
        
      • public class Demo15Continue {
        	public static void main(String[] args) {
        		for (int i = 1; i <= 10; i++) {
        			if (i == 4) { // 如果当前是第4层
        				continue; // 那么跳过当前次循环,马上开始下一次(第5层)
        			}
        			System.out.println(i + "层到了。");
        		}
        	}
        }
        

6.扩展

  • ​ 死循环

    永远停不下来的循环,叫做死循环。

  • 格式:

    while (true) {
    	循环体
    }
    
  • 代码:

    public class Demo16DeadLoop {
    	public static void main(String[] args) {
    		while (true) {
    			System.out.println("I Love Java!");
    		}
    		
    		// System.out.println("Hello");
    	}
    }
    
  • 嵌套循环

    所谓嵌套循环,是指一个循环的循环体是另一个循环。比如for循环里面还有一个for循环,就是嵌套循环。总 共的循环次数=外循环次数*内循环次数

  • 嵌套循环的格式:

    for(初始化表达式①; 循环条件②; 步进表达式⑦) { 
    	for(初始化表达式③; 循环条件④; 步进表达式⑥) {
        	执行语句⑤; 
        } 
      }
    
  • 嵌套循环的执行步骤:

    • 执行顺序:

      • ①②③④⑤⑥>④⑤⑥>⑦②③④⑤⑥>④⑤⑥
      • 外循环一次,内循环多次。
      • 比如跳绳:一共跳5组,每组跳10个。5组就是外循环,10个就是内循环。
    • 练习一 :使用嵌套循环,打印5*8的矩形

      • 5 * 8 可以理解为 5列 8 行 , 一行打印5个 * ,打印 8 次;

        public class Print {
            public static void main(String[] args) {
            	//外循环控制打印次数 也就是 8 行
                for (int i = 0; i < 8; i++) {
                	// 内层控制每行打印的 * 个数
                    for (int j = 0; j < 5; j++) {
                        System.out.print("*");
                    }
                System.out.println();
                }
            }
        }
        
        结果:
        
        *****
        *****
        *****
        *****
        *****
        *****
        *****
        *****
        
    • 练习二 : 模拟时钟打印时间

      public class Demo17LoopHourAndMinute {
      	public static void main(String[] args) {
      		for (int hour = 0; hour < 24; hour++) { // 外层控制小时
      			for (int minute = 0; minute < 60; minute++) { // 内层控制小时之内的分钟
      				System.out.println(hour + "点" + minute + "分");
      			}
      
      		}
      	}
      }
      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值