第七节 选择结构

选择结构

if语句

用if语句根据考试成绩判断成绩等级

public class If {
    public static void main (String [] args){
        int score = 60;
        if (score >= 85 && score <= 100){
            System.out.println("你的成绩属于优秀");}
        else if (score >= 70 && score <85){
            System.out.println("你的成绩属于良好");
        }
        else if (score >= 60 && score <70){
            System.out.println("你的成绩属于一般");
        }
        else if (score <60 && score >= 0) {
            System.out.println("你的成绩属于不及格");
        }
        else {
            System.out.println("你的成绩是错误的");
        }

    }
}

用if语句替代三元运算符

题目:用三元运算符和if语句分别实现:求两个数中的最大值。

//三元运算符
public class If {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        int max =  a>b ? a:b;
        System.out.println("最大值是:"+max);
    }
}
//if语句
public class If {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        if (a>b) {
            System.out.println("最大值是:"+a);
        }
        else {
            System.out.println("最大值是:"+b);
        }
    }
}

switch语句

注意事项

  1. 多个case后面的数值不可以重复
  2. switch后面的小括号只能是下列数据类型:
    1. 基本数据类型:byte/short/char/int
    2. 引用数据类型 String字符串、enum枚举
  3. switch语句格式可以很灵活:前后顺序可以颠倒,break可以省略

switch语句的穿透性

匹配到哪个case就从哪一个位置向下执行,直到遇到了break或者整体结束为止。

//最终输出结果: 大家好
public class Switch {
    public static void main (String [] args){
        int num = 5;
        switch (num){
            case 1:
                System.out.println("你好");
                break;
            case 2:
                System.out.println("我好");
                break;
            case 3:
                System.out.println("他好");
                break;
            default: 
                System.out.println("大家好");
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值