//三元运算符的练习1
package test;
import java.util.Scanner;
public class Test3 {
public static void main(String[] args) {
/*
需求:动物园里有两只老虎,体重分别通过键盘录入获得
请用程序实现判断两个老虎的体重是否相同
*/
//分析:
//1.键盘录入两只老虎体重
Scanner sc = new Scanner(System.in);
System.out.println("请输入第一只老虎的体重");
int weight1 = sc.nextByte();
System.out.println("请输入第二只老虎的体重");
int weight2 = sc.nextByte();
//2.比较
String result = weight1 == weight2 ? "相同" : "不相同";
System.out.println(result);
}
}
//三元运算符练习2
package test;
public class Test3a {
public static void main(String[] args) {
/*
需求:一个寺庙住这三个和尚,已知他们的身高分别为150cm,210cm,165cm,
请用程序实现这三个和尚的是最高身高
*/
//1.定义三个变量记录三个和尚的身高
int height1 = 150;
int height2 = 210;
int height3 = 165;
//2.那第一个和尚和第二个和尚进行比较
int temp = height1 > height2 ? height1 : height2;
int max = temp > height3 ? temp : height3;
System.out.println(max);
//Ctrl+Alt+L(代码对齐)
//再拿着结果跟第三个和尚进行比较即可
}
}
Java三元运算符的两个相关练习
最新推荐文章于 2024-07-28 19:41:52 发布