三元运算符
三个元素参与的运算符,第一个“condition”必须为布尔型
得到布尔型的方式:
- 直接true&false
- 比较
- 逻辑运算
condition ? exp1 : exp2
condition为真时计算exp1的值,否则计算exp2的值。
例子
public class TestOperator {
public static void main(String[] args) {
int score = 80;
String passOrNot = score >= 60 ? "及格" : "不及格";
System.out.println("Score = "+score + "时,我们认为成绩: " + passOrNot);
//Score = 80 时,我们认为成绩及格
int score1 = 59;
String passOrNot = score >= 60 ? "及格" : "不及格";
System.out.println("Score = "+score + "时,我们认为成绩: " + passOrNot);
//Score = 59 时,我们认为成绩: 不及格
}
}
区分优秀和合格
public class TestOperator {
public static void main(String[] args) {
int score = 80;
String passOrNot = score >= 60 ? (score >= 85 ? "优秀" : "合格") : 不及格);
System.out.println("Score = "+score + "时,我们认为成绩: " + passOrNot);
//Score = 80 时,我们认为成绩: 优秀
}
}