三元运算符

 1 package day02;
 2 
 3 public class DemoThree01 {
 4     /*三元运算符:格式:关系表达式?表达式1:表达式2;
 5     * 执行流程:首先计算关系表达式的值,如果值为true取表达式1的值;如果为false取表达式2的值
 6     * 需求:求两个变量的最大值*/
 7     public static void main(String[] args) {
 8         int a =11;
 9         int b =21;
10         int min = a > b ? b :a;
11         System.out.println(min);
12     }
13 }

执行结果:

 eg:

 1 package day02;
 2 
 3 public class DemoThree02 {
 4         /*
 5             1. 定义三个变量用于保存运动员的身高
 6             2. 用三元运算符 , 比较前两个变量,获取较大值。
 7             3. 用三元运算符 , 让较大值和第三个变量比较,获取最大值。
 8             4. 输出结果
 9 
10         */
11         public static void main(String[] args) {
12             // 1. 定义三个变量用于保存运动员的身高
13             int a = 150;
14             int b = 210;
15             int c = 165;
16 
17             // 2. 用三元运算符 , 比较前两个变量,获取较大值。
18             int tempMax = a > b ? a : b;
19 
20             // 3. 用三元运算符 , 让较大值和第三个变量比较,获取最大值。
21             int max = tempMax > c ? tempMax : c;
22 
23             // 4. 输出结果
24             System.out.println(max);
25 
26             int result = a > b ? a : b > c ? a > b ? a : b : c;
27 
28             System.out.println(result);
29         }
30     }

执行结果:

欢迎批评指正,提出问题,谢谢!
原文地址:https://www.cnblogs.com/xxeleanor/p/14195000.html