三元运算符
开始复习三元运算符,因为感觉变量和基本运算符这些应该不用复习了,就省略了,因为我看的是黑马的课,所以案例就直接用黑马的案例了,嘻嘻嘻
三元运算符
- 格式:关系表达式 ? 表达式1 : 表达式2
- 范例:
a > b ? a : b
计算规则:
首先计算关系表达式的值
如果值为true,表达式1的值就是运算结果
如果值为false,表达式2的值就是运算结果
代码实例:
public class demo {
public static void main(String[] args) {
//定义两个变量
int a = 10;
int b = 20;
//获取两个数据中的最大值
int max = a > b ? a : b;
//输出结果
System.out.println("最大值为:" + max);
}
}
运算结果为:
最大值为:20
案例:两只老虎
需求:动物园里有两只老虎,已知两只老虎的体重分别是180kg、200kg,请用程序实现判断两只老虎的体重是否相同
分析:
① 定义两个变量用于保存老虎的体重,单位为kg,这里仅仅体现数值即可。
int weight1 = 180;
int weight2 = 200;
② 用三元运算符实现老虎体重的判断,体重相同,返回true,否则,返回false。
(weight1 == weight2) ? true : false;
③ 输出结果
代码实例:
public class demo {
public static void main(String[] args) {
//定义两个变量
int weight1 = 180;
int weight2 = 200;
//获取两个数据中的最大值
boolean b = (weight1 == weight2) ? true : false;
//输出结果
System.out.println("两只老虎体重是否相等:" + b);
}
}
运算结果:
两只老虎体重是否相等:false
案例:三个和尚
需求:一座寺庙里住着三个和尚,已知他们的身高分别是150cm、210cm、165cm,请用程序实现获取这三个和尚的最高身高
分析:
① 定义三个变量用于保存和尚的身高,单位为cm,这里仅仅体现数值即可。
int height1 = 150;
int height2 = 210;
int height3 = 165;
② 用三元运算符获取前两个和尚的较高身高,并用临时身高变量保存起来。
tempHeight = (height1 > height2) ? height1 : height2;
③ 用三元运算符获取临时身高和第三个和尚的身高较高者,并用最大身高变量保存。
maxHeight = (tempHeight > height3) ? tempHeight : height3;
④ 输出结果。
代码示例:
public class demo {
public static void main(String[] args) {
//定义三个变量用于保存和尚的身高,单位为cm,这里仅仅体现数值即可。
int height1 = 150;
int height2 = 210;
int height3 = 165;
//用三元运算符获取前两个和尚的较高身高,并用临时身高变量保存起来。
int tempHeight = (height1 > height2) ? height1 : height2;
//用三元运算符获取临时身高和第三个和尚的身高较高者,并用最大身高变量保存。
int maxHeight = (tempHeight > height3) ? tempHeight : height3;
//输出结果
System.out.println("maxHeight:" + maxHeight);
}
}
运行结果:
maxHeight : 210