Java-运算符_三元运算符
一、三元运算符
1.三元运算
- 格式:
关系运算符?表达式1:表达式2; - 举例:
a > b ? a : b;
2.规则
首先计算关系表达式的值
如果值为true,表达式1的值就是运算结果
如果值为false,表达式2的值就是运算结果
二、代码
三元运算符
public class OperatorDemo9 {
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = a > b ? a : b;
System.out.println(c);
}
}
两只老虎
public class OperatorDemo10 {
public static void main(String[] args) {
// 定义两只老虎的重量
int tiger1 = 180;
int tiger2 = 200;
// 三元运算符作比较
// result来接收结果
boolean result = tiger1 > tiger2 ? true : false;
System.out.println(result);
}
}
三个和和尚
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
/**
* @Author: nsys
* @Date: 2021-10-04 9:03
* @Description: 三个和尚
*/
public class OperatorDemo11 {
public static void main(String[] args) {
// 定义三个和尚的身高
int person1 = 155;
int person2 = 185;
int person3 = 177;
// 使用三元运算,两两对比
int temp = person1 > person2 ? person1 : person2;
int personMax = temp > person3 ? temp : person3;
System.out.println(personMax);
}
}

浙公网安备 33010602011771号