1.使用三元运算符完成如下练习(以int类型数据为例,数字要求键盘录入)
(1)比较两个数是否相等
import java.util.Scanner;
class Zuo {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数");
int x = sc.nextInt();
System.out.println("请输入第二个数");
int y = sc.nextInt();
boolean b = (x == y);
System.out.println(b);
}
}
(2)获取两个数中最小值
import java.util.Scanner;
class Zuo {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数");
int x = sc.nextInt();
System.out.println("请输入第二个数");
int y = sc.nextInt();
int min = (x < y)? x : y;
System.out.println(min);
}
}
(3)获取三个数中最小值(考虑能否用一条三元运算符实现)
import java.util.Scanner;
class Zuo {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一个数");
int x = sc.nextInt();
System.out.println("请输入第二个数");
int y = sc.nextInt();
System.out.println("请输入第三个数");
int z = sc.nextInt();
int min = (x < y)? x : y;
int zmin = (min < z)? min : z;
System.out.println(zmin);
}
}
|
|