1、三元(目)運算符的格式:(關係運算符) ?表達式1 :表達式2
根據關係運算符的結果,來判斷,如果關係運算符的結果爲true,則值爲表達式1,否則爲表達式2。
2、用三元表達:式取兩個數最大值
public static void main(String[] args){
int x = 10;
int y = 5;
int z;
z = (x > y) ? x : y;
System.out.println(z); //10
}
3、案例:比較兩個整數是否相同:
public static void main(String[] args){
int x = 10;
int y = 5;
String b = (x == y) ? "相等" : "不相等";
System.out.println(b); //false
}
4、案例:比較三個整數中的最大值:
public static void main(String[] args){
int x = 10;
int y = 5;
int z = 15;
int t = (x > y) ? x : y;
int m = (t > z) ? t : z;
System.out.println(m);
}