第三章: 运算符
1. 算数运算符
1.1 概述
- 加减乘除: + ,- ,* ,/ ,~/ , %
- 递增递减: ++var ,var++ ,--var ,var--
1.2 代码示例
void main() {
int a = 10;
int b = 2;
print(a + b); //12
print(a - b); //8
print(a * b);//20
print(a / b);//5.0
print(a ~/ b);//5
print(a % b);//0
print(a++); //10 a=10-> print-> a=11
print(++a); //12 a=11-> a=12-> print
print(a--); //12 a=12-> print-> a=11
print(--a); //10 a=11-> a=10-> print
}
2. 关系运算符
2.1 概述
- 运算符:==, !=, >, <, >=, <=
- 判断内容是否相同使用==
2.2 代码示例
void main() {
int a = 5;
int b = 3;
print(a == b); //false
print(a != b); //true
print(a > b); //true
print(a < b); //false
print(a >= b); //true
print(a <= b); //false
String strA = "123";
String strB = "123";
print(strA == strB); //true 比较内容
}
3. 逻辑运算符
3.1 概述
- 运算符: !, &&, ||
- 针对布尔类型运算
3.2 代码示例
void main() {
bool isTrue = true;
print(!isTrue); //false
bool isFalse = false;
print(isTrue && isFalse); //false
print(isTrue || isFalse); //true
String str = "";
print(!str.isEmpty); //false
}
4. 赋值运算符
4.1 概述
基础运算符: =, ??=
复合运算符: +=, -=, *= , /=, %= , ~/=
4.2 代码示例
void main() {
var a = 10;
int b = 10;
var c = null;
c ??= 10;
print(c); //10 相当于kotlin中的 c?.(operate)?:10
a += 2;
print(a); //12
a -= b;
print(a); //2
a *= b;
print(a); //20
//a /= b;
//print(a) //无法运算,因为结果是0.0会成为double类型,所以无法赋值给int类型的a
a ~/= b;
print(a); //2
a % b;
print(a); //2
}
5. 条件运算符
5.1 概述
三目运算符: condition ? expr1 : expr2
??运算符: expr1 ?? expr2
5.2 代码示例
void main() {
int gender = 1;
String str = gender == 0 ? "Male= $gender" : "Female= $gender";
print(str); //Female= 1
String a = "Dart";
String b = "Java";
String c = a ?? b;
print(c); //Dart
}