教你如何区别if else和switch case
注意: if…else会生成一个跳转表来指示实际的case分支的地址,而switch case却需要遍历条件分支直到命中条件。
一. if else的优缺点
(1)if else的优点:if else能应用于更多的场所以if else比较灵活 。
(2)if else的缺点:if else必须遍历所以得可能值。
二. switch case的优缺点
(1)switch case的优点:当分支较多时,用switch的效率是很高的。因为switch是确定了选择值之后直接跳转到那个特定的分支.
(2)switch case的缺点:switch…case占用较多的代码空间,因为它要生成跳表,特别是当case常量分布范围很大但实际有效值又比较少的情况,switch…case的空间利用率将变得很低。
注意;switch…case只能处理case为常量的情况。
三.具体案列的实现
(1)题目内容
01;积分转换段位: 王者荣耀段位判断
50分以下倔强青铜
50-60 秩序白银
60-70 黄金
70-80 铂金
80-90 钻石
90-100 星曜
100以上 王者
可以使用if或者switch(挑战)
(2)0.1 题目分析方法一 0.2 题目分析方法二
命名一个数组名称 math
50分以下倔强青铜 math<50
50-60 秩序白银 math>=50 && math<60 10 取整数
60-70 黄金 math>=60 && math<70 ****
70-80 铂金 math>=70 && math<80 ****
80-90 钻石 math>=80 && math<90 ****
90-100 星曜 math>=90 && math<100 ****
100以上 王者 math>=100 ****
(3)01用代码表示法一
public class Text01 {
// 单行注释 程序的入口
public static void main(String[] ages) {
// 创建键盘扫描器
Scanner scan = new Scanner(System.in);
boolean flag = true;
while (flag) {
// 提示用户输出信息
System.out.println("========尊敬的Vip玩家欢迎来到王者荣耀段位查询平台==========\n请输入你的王者积分");
int math=scan.nextInt();
if(math<=50) {
System.out.println("尊敬的Vip玩家你当前段位为: 倔强青铜");
}else if(math>50 && math<=60) {
System.out.println("尊敬的Vip玩家你当前段位为: 秩序白银");
}else if(math>60 && math<=70) {
System.out.println("尊敬的Vip玩家你当前段位为: 黄金");
}else if(math>70 && math<=80) {
System.out.println("尊敬的Vip玩家你当前段位为: 铂金");
}else if(math>80 && math<=90) {
System.out.println("尊敬的Vip玩家你当前段位为: 钻石");
}else if(math>90 && math<=100) {
System.out.println("尊敬的Vip玩家你当前段位为: 星曜");
}else{
System.out.println("尊敬的Vip玩家你当前段位为: 王者");
}
}
}
}
01.1运行效果图
02用代码表示法二
public class Text01 {
// 单行注释 程序的入口
public static void main(String[] ages) {
// 创建键盘扫描器
Scanner scan = new Scanner(System.in);
boolean flag = true;
while (flag) {
// switch(挑战)
System.out.println("尊敬的Vip玩家请输入你的王者积分");
int integral = scan.nextInt();
switch (integral / 10) {
case 0:
case 1:
case 2:
case 3:
case 4:
System.out.println("你当前段位为: 倔强青铜 ");
break;
case 5:
System.out.println("你当前段位为: 秩序白银 ");
break;
case 6:
System.out.println("你当前段位为: 黄金 ");
break;
case 7:
System.out.println("你当前段位为: 铂金 ");
break;
case 8:
System.out.println("你当前段位为: 钻石 ");
break;
case 9:
System.out.println("你当前段位为: 星曜 ");
break;
default:
System.out.println("你当前段位为: 王者");
}
}
}
}
02.1运行效果图
小伙伴们今日分享就到此结束,要想了解更多请关注我,持续为你更新奥!