Conditional operator
Also known as ternary operator/ternary operator
Format: a?b:c
Where a is a boolean expression, the return result is either true or false, and the final expression result is determined by the result of a:
if the result of a is true , then the final result of the expression is b .
If the result of a is false , then the final result of the expression is c .
- Can replace if...else... statement
public class TestOpe13{
public static void main(String[] args){
int num=(5>7)?6:9;
System.out.println(num);
}
}
Calculation result:
Exercise:
import java.util.*; public class TestOpe14{ public static void main(String[] args){ //实现功能:男孩女孩选择晚饭吃什么,如果意见一致听男生的,如果意见不一致,听女生的。 System.out.println("请选择今晚吃什么:1.火锅 2.烧烤 3.麻辣烫"); Scanner sc=new Scanner(System.in); //男孩选择 System.out.println("请男孩选择:"); int boyChoice=sc.nextInt(); //女孩选择 System.out.println("请女孩选择:"); int girlChoice=sc.nextInt(); //判断 System.out.println(boyChoice==girlChoice?"听男孩的":"听女孩的"); } }
operation result: