条件运算符(三目运算符)

/*
 * 条件运算符(三目运算符)
 */
/*
 * 语法格式:
 * x?y:z;
 * 其中x为boolean类型表达式,先计算x的值,若为true,则整个运算的结果为y的值,否则整个运算结果的值为z的值
 */
public class Pro02 {
	public static void main(String[]args) {
		int score=80;
		int x=-100;
		String type=score<60?"不及格":"及格";//后面跟的两个y、z可以是任意类型,但是x必须是boolean类型
		System.out.println(type);
		/*
		if(score<60) {
			System.out.println("不及格");
		}else {
			System.out.println("及格");
		}
		*///此时上面的条件运算符的功能相当于此if else语句的功能
		System.out.println(x>0?1:(x==0?0:-1));//从左向右推理,-100不大于0,即为false,输出(x==0?0:-1),-100不等于0,即返回-1
		
		
	}
	/*
	 	输出结果如下:
	 	及格
		-1
	 */

}

猜你喜欢

转载自blog.csdn.net/sdau20171761/article/details/82963288