Lesson 07
循环Loops
循环控制
循环 内嵌 if 语句
可以内嵌 if 语句, 实现循环时达到分支效果
1 2 3 4 5 for (...){ if (...) { }}
挑战
基于下面的代码。写 循环输出
1 2 int[] arr = {6, 7, 3, 8, 4};// todo
使得输出
6, 7, 3, 8, 4
循环 与 boolean 运算 做假设验证
1 2 3 4 5 6 boolean test = false;for (...){ if (...) { test = true; }}
特性
只有每次循环,if
语句条件都不成立时,test
才会是 false
假设一个很难证明的
条件内赋值一个很好推翻的
挑战
检测数组里是否有 0,输出 true
或者 false
break 控制
立刻停止下面语句, 跳出循环
一般内嵌在条件语句里
代码
1 for (2; 3; 4){ 51 if (52) { break; } 53 } 6
执行顺序
1 2 3 51 52 53 4 3 51 52 break 7
continue 控制
立刻停止下面语句, 尝试下次循环
一般内嵌在条件语句里
代码
1 for (2; 3; 4){ 51 if (52) { continue; } 53 } 6
执行顺序
1 2 3 51 52 53 4 3 51 52 continue 4 3 51 52 53 4 3 7
while 语句
用途
用于执行不确定次数的重复
while
语法
while (<condition>) { <statements> }
while
执行顺序
1 while (2) { 3 } 4
1 2 32 32 ... 32 4
3 有没有可能不执行
A. 有, B. 没有
do while
语法
do { <statements> } while (<condition);
do while
执行顺序
1 do { 2 } while (3) 4
1 23 23 ... 23 4
2 有没有可能不执行
A. 有, B. 没有
案例
随机生成一个 1 - 9 之间的奇数
随机
1 new Random().nextInt(10);
会返回 0 ~ 9 之间的整数
while 循环控制
死循环
1 2 3 while(true) { ...}
跳出循环
1 2 3 4 5 6 7 while(true) { ... if (...) { break; } ...}
其它
while 里 也可以写 continue
while 语句技巧
需求
< < > < > < >我说鸡蛋,你说要鸡蛋要鸡蛋要 鸡蛋不要
1. 原始代码
写出非循环版本
1 2 3 4 5 6 7 Console.println("我说鸡蛋,你说要");Console.println("鸡蛋");Console.nextLine();Console.println("鸡蛋");Console.nextLine();Console.println("鸡蛋");Console.nextLine();
2. 死循环
找到重复单元,套在 死循环里
1 2*3 4 5*Console.println("我说鸡蛋,你说要");while(true) { Console.println("鸡蛋"); Console.nextLine();}
3. 找出口
找到跳出情况,写 if break
1 2 3 4*5+6+7+8 Console.println("我说鸡蛋,你说要");while(true) { Console.println("鸡蛋"); Stirng command = Console.nextLine(); if (!command.equals("要")) { break; }}
4. 确认次数
确认次数是否正确
5. 简化
如果 if break
在 最后一句,可以转为 do while condition
如果 if break
在 第一句,可以转为 while condition
其它情况,不能简化
1 2 3 4 5 6 Console.println("我说鸡蛋,你说要");Stirng command;do { Console.println("鸡蛋"); command = Console.nextLine();} while (command.equals("要"));
挑战
根据要的次数,在最后输出金额,一个鸡蛋 2 元。
while
语句对比
while
和 do while
的区别
while
先检查,再执行,有可能不执行
do while
先执行,再检查,保障至少执行一次
while
和 for
的区别
for
用于 知道 次数的循环 更贴切
while
用于 不知道 次数的循环 更贴切
for
与 while
互转
for
转 while
1 for(2; 3; 4) { 5 } 6
可转为
1 2 while(3) { 5 4 } 6
前提是里面没有 continue 或者 break
案例分析
输出一个数组里的值,遇到 0 就停,不输出 0
程序会因为 不确定的 0 的出现 而停止
程序也会因为 确定的 元素结束 而停止
for 与 while 版本对比
作业
C - A 级
建议先做这个作业