三元运算符
/*
两只老虎
需求:动物园里有两只老虎体重分别为180kg, 200kg
判断两只老虎的体重是否相同
*/
public class TwoTigers {
public static void main(String[] args) {
//1.定义两个变量用于保存老虎的体重
int weight1 = 180;
int weight2 = 200;
//2.用三元运算符判断老虎体重,若相同则返回true
boolean b = weight1 == weight2 ? true : false;
//3.输出结果
System.out.println("b:" + b);
}
}
/*
三个和尚
需求:一座寺庙里住着三个和尚,身高分别为150cm, 160cm,170cm
求出这三个和尚的最高身高
*/
public class ThreeBuddhist {
public static void main(String[] args) {
//1.定义三个变量保存和尚的身高
int height1 = 150;
int height2 = 160;
int height3 = 170;
//2.用三元运算符获取前两个和尚的较高身高
int tempHeight = height1 > height2 ? height1 : height2;
//3.用三元运算符获取最高身高
int maxHeight = tempHeight > height3 ? tempHeight : height3;
//4.输出结果
System.out.println("maxHeight = " + maxHeight);
}
}