格式:
变量=condition ? value1 : value2
condition是一个布尔表达式,如果为true,则返回value1,否则返回value2
比如:变量a的赋值,如果x>y,则a=1,否则,a=2
用if else代码如下:
1 import java.util.Random; 2 public class Test3 { 3 public static void main(String[] args){ 4 Random random = new Random(); 5 int x = random.nextInt(10);//生成[0,9]的随机整数 6 int y = random.nextInt(10);//生成[0,9]的随机整数 7 System.out.println("x为"+x); 8 System.out.println("y为"+y); 9 int a; 10 if (x > y) { 11 a = 1; 12 }else { 13 a = 2; 14 } 15 System.out.println("a为"+a); 16 } 17 }
等效的三目运算符书写如下:
1 import java.util.Random; 2 public class Test3 { 3 public static void main(String[] args){ 4 Random random = new Random(); 5 int x = random.nextInt(10);//生成[0,9]的随机整数 6 int y = random.nextInt(10);//生成[0,9]的随机整数 7 System.out.println("x为"+x); 8 System.out.println("y为"+y); 9 int a; 10 //三目运算符的写法 11 a=x>y?1:2; 12 System.out.println("a为"+a); 13 } 14 }
多条件也一样适用
比如:变量a的赋值,如果x>y,则b=1,x=y,则b=2,否则(x<y),b=3
import java.util.Random; public class Test3 { public static void main(String[] args){ Random random = new Random(); int x = random.nextInt(10);//生成[0,9]的随机整数 int y = random.nextInt(10);//生成[0,9]的随机整数 System.out.println("x为"+x); System.out.println("y为"+y); int b; //变量b的赋值,如果x>y,则b=1,x=y,则b=2,否则(x<y),b=3 //if else的写法 if (x > y) { b = 1; }else if(x == y){ b = 2; }else { b =3; } System.out.println("b为"+b); } }
等效的三目运算符书写如下:
import java.util.Random; public class Test3 { public static void main(String[] args){ Random random = new Random(); int x = random.nextInt(10);//生成[0,9]的随机整数 int y = random.nextInt(10);//生成[0,9]的随机整数 System.out.println("x为"+x); System.out.println("y为"+y); int b; //变量b的赋值,如果x>y,则b=1,x=y,则b=2,否则(x<y),b=3 //三目运算符的写法 b=(x>y)?1:(x==y)?2:3; System.out.println("b为"+b); } }
标签:Random,java,int,random,System,运算符,三目,println,out From: https://www.cnblogs.com/luoshuai7394/p/17894413.html