第5节运算符练习
案例:两只老虎
需求:动物园里有两只老虎,已知两只老虎的体重分别为180kg、200kg,
请用程序实现判断两只老虎的体重是否相同。

分析:
1、定义两个变量用于保存老虎的体重,单位为kg,这里仅仅体现数值即可。
int weight1=180;
int weight2=200;
2、用三元运算符实现老虎体重的判断,体重相同,返回true,否则,返回false。
(weight1==weight2)?true:false;
3、输出结果
/* 两只老虎 需求: 动物园里有两只老虎,已知两只老虎的体重分别为180kg、200kg, 请用程序实现判断两只老虎的体重是否相同。 */ public class OperatorDemo10{ public static void main(String[] args){ //定义两个变量用于保存老虎的体重,单位为kg,这里仅仅体现数值即可。 int weight1=180;//weight[weIt]重量 int weight2=200; //用三元运算符实现老虎体重的判断,体重相同,返回true,否则,返回false。 boolean agree = (weight1 == weight2) ? true : false; //输出结果 System.out.println("结果:"+agree); } }
案例:三个和尚
需求:一个寺庙里住着三个和尚,已知他们的身高分别为150cm、
210cm、165cm,请用程序实现获取这三个和尚的最高身高。

分析:
1、定义三个变量用于保存和尚的身高,单位为cm,这里仅仅体现数值即可。
int height1=150;
int height2=210;
int height3=165;
2、用三元运算符获取前两个和尚的较高身高值,并用临时变量保存起来。
(height1>height)?height1:height2;
3、用三元运算符获取临时身高值和第三个和尚身高较高值,并用最大身高变量保存。
(tempHeight>height3)?tempHeight:height3;
4、输出结果
/* 三个和尚 需求: 一个寺庙里住着三个和尚,已知他们的身高分别为150cm、 210cm、165cm,请用程序实现获取这三个和尚的最高身高。 */ public class OperatorDemo11{ public static void main(String[] args){ //定义三个变量用于保存和尚的身高,单位为cm,这里仅仅体现数值即可。 int height1=150;//height[haIt]高度 int height2=210; int height3=165; //用三元运算符获取前两个和尚的较高身高值,并用临时变量保存起来。 int tempHeight = (height1 > height2) ? height1 : height2; //用三元运算符获取临时身高值和第三个和尚身高较高值,并用最大身高变量保存。 int max = (tempHeight>height3) ? tempHeight : height3; //输出结果 System.out.println("最高身高:" + max + "cm"); } }
数据输入
数据输入概述

Scanner使用的基本步骤
1、导包
import java.util.Scanner;
导包的动作必须出现在类定义的上边
2、创建对象
Scanner sc=new Scanner(System.in);
上面这个格式里面,只有sc是变量名,可以变,其他的都不允许变。
3、接收数据
int i=sc.nextInt();
上面这个格式里面,只有i是变量名,可以变,其他的都不允许变。
/* 数据输入: 导包: import java.util.Scanner; 创建对象: Scanner sc=new Scanner(System.in); 接收数据: int x=sc.nextInt(); */ import java.util.Scanner; public class ScannerDemo{ public static void main(String[] args){ //创建对象 Scanner sc=new Scanner(System.in); //接收数据 int i=sc.nextInt(); //输出数据 System.out.println("i:"+i); } }
案例:三个和尚升级版
需求:一个寺庙住着三个和尚,他们的身高必须经过测量得出,
请用程序实现获取这三个和尚的最高身高。

分析:
1、身高未知,采用键盘录入实现。首先导包,然后创建对象。
import java.util.Scanner;
Sacnner sc=new Scanner(System.in);
2、键盘录入三个身高分别赋值给三个变量。
int height1=sc.nextInt();
int height2=sc.nextInt();
int height3=sc.nextInt();
3、用三元运算符获取前两个和尚的较高身高值,并用临时身高变量保存起来。
(height1>height2)?height1:height2;
4、用三元运算符获取临时身高值和第三个和尚身高较高值,并用最大身高变量保存。
(tempHeight>height3)?tempHeight:height3;
5、输出结果
import java.util.Scanner; public class ScannerDemo02{ public static void main(String[] args){ //创建对象 Scanner sc=new Scanner(System.in); //接收三个和尚的身高数据 System.out.println("请输入第一个和尚的身高:"); int height1=sc.nextInt(); System.out.println("请输入第二个和尚的身高:"); int height2=sc.nextInt(); System.out.println("请输入第三个和尚的身高:"); int height3=sc.nextInt(); //用三元运算符进行比较1和2较高的值 int tempHeight=(height1>height2)?height1:height2; //用三元运算符比较最高的值 int max=(tempHeight>height3)?tempHeight:height3; //输出结果 System.out.println("三个和尚的最高身高为:"+max+"cm"); } }

浙公网安备 33010602011771号