三个和尚比身高案例
一个寺庙里住着三个和尚,他们的身高经过测量得出,用Java程序获取这三个和尚中的最高身高。
分析:这里我们会用到键盘录入实现,然后用三元运算符来进行两次比较。
代码
import java.util.Scanner;//导包
public class Shengao{
public static void main(String[] args){
//键盘录入,创建对象
Scanner sc = new Scanner(System.in);
//键盘录入三个身高赋值
System.out.println("请输入第一个和尚的身高:");
int heigh1 = sc.nextInt();
System.out.println("请输入第二个和尚的身高:");
int heigh2 = sc.nextInt();
System.out.println("请输入第三个和尚的身高:");
int heigh3 = sc.nextInt();
//用三元运算符获取前两个前两个和尚的较高身高值,并用临时身高变量暂时保存起来
int tempHeigh = heigh1 > heigh2 ? tempHeight : height;
//用临时身高边量与第三个和尚比较
int tempHeigh = tempHeight > heigh3 ? tempHeight : height3;
//输出结果
System.out.println("这三个和尚中身高最高的是:" + maxHeight + "cm");
}
}
这样利用键盘录入和三元运算符就可以比较出这三个和尚的身高最高值。