格式:
关系表达式?表达式1:表达式2;
范例:
a > b ? a : b;
执行流程:
首先计算关系表达式的值
如果值为true,表达式1的值就是运算结果
如果值为false,表达式2的值就是运算结果
案例一:
public class Firstproj {
public static void main(String[] args) {
//定义两个变量
int a = 10;
int b = 20;
//获取两个数据中的较大值
int max = a > b ? a : b;
//输出结果
System.out.println("max="+max);
}
}
结果:
案例二:
public class Firstproj {
public static void main(String[] args) {
int score=80;
String type =score<60?"不及格":"及格";
System.out.println(type);
}
}
结果:
案例三:
public class Firstproj {
public static void main(String[] args) {
int x = -10;
System.out.println(x>0?1:(x==0?0:-1));
}
}
结果: