第四章:控制语句 1. if语句 1.1 概述 1.2 代码示例 2. for语句 2.1 概述 2.2 代码示例 3. while语句 3.1 概述 3.2 代码
第四章:控制语句
- 1. if语句
- 1.1 概述
- 1.2 代码示例
- 2. for语句
- 2.1 概述
- 2.2 代码示例
- 3. while语句
- 3.1 概述
- 3.2 代码示例
- 4. break和continue
- 4.1 概述
- 4.2 代码示例
- 5. switch和case
- 5.1 概述
- 5.2 代码示例
1. if语句
1.1 概述
- if语句- if..else if语句
- if..else i..else语句
1.2 代码示例
void main() {int score = 100;//完美
if (score >= 90) {
if (score == 100) {
print("完美");
} else {
print("优秀");
}
} else if (score > 60) {
print("良好");
} else if (score == 60) {
print("及格");
} else
print("不及格");
//完美
}
2. for语句
2.1 概述
- for循环- for..in循环
2.2 代码示例
void main() {var list = [1, 2, 3, 4, 5];
for (var index = 0; index < list.length; index++) {
print(list[index]);
}
print("---------");
for (var item in list) {
print(item);
}
/**
* 输出:
* 1
2
3
4
5
---------
1
2
3
4
5
*/
}
3. while语句
3.1 概述
- while循环- do...while循环
3.2 代码示例
void main() {int count = 0;
while (count < 5) {
print(count++);
}
print("----$count----");
do {
print(count--);
} while (count > 0 && count < 5);
/**
* 输出:
* 0
1
2
3
4
----5----
5
4
3
2
1
*/
}
4. break和continue
4.1 概述
- 终止循环:break- 跳出当前循环:continue
4.2 代码示例
void main() {var list = [1, 2, 3];
for (var item in list) {
if (item == 1) {
//break;
continue;
}
print(item);
}
/**
* 输出:
* 2
3
*/
print("-----");
var list2 = [4, 5, 6];
for (var item1 in list) {
if (item1 == 2) {
break;
}
for (var item2 in list2) {
if (item2 == 5) {
break;
}
print(item2);
}
}
//4
}
5. switch和case
5.1 概述
- 比较类型: num , String ,编译期常量,对象,枚举- 非空case必须有一个break
- default处理默认情况
- continue跳转标签
5.2 代码示例
void main() {String language = "Java";
switch (language) {
case "Dart":
print("Dart is my favorite");
break;
case "Java":
print("Java is my favorite");
break;
case "Python":
print("Python is my favorite");
break;
default:
print("None");
} //Java is my favorite
switch (language) {
Test:
case "Dart":
print("Dart is my favorite"); //3.再打印
break; //4.跳出
case "Java":
print("Java is my favorite"); //1.先打印
continue Test; //2.跳到Test:
//break;
case "Python":
print("Python is my favorite");
break;
default:
print("None");
}
/**
* 输出:
* Java is my favorite
Dart is my favorite
*/
}