Java的switch case

在jdk1.7以后, switch() 中的变量类型只能为 string,int,short,byte,char,Integer,Character,enum 类型,其他类型运行会报错.

switch case语句基本格式为:

switch(变量){
    case 变量值1:
        //逻辑
        break;
    case 变量值2:
        //逻辑
        break;
    ...
    case 变量值n:
        //逻辑
        break;
    default:
        //逻辑
        break;

}

执行过程分为几种情况:

    情况一:

        int i = 1;
        switch (i) {
            case 0:
                System.out.println("i = 0");
                break;
            case 1:
                System.out.println("i = 1");
                break;
            case 2:
                System.out.println("i = 2");
                break;
            default:
                System.out.println("i 值未确定");
                break;
        }

    当含有 breakcase值 找到, run: i = 1  ---  若未找到 run : i 值未确定 ,既执行 default 语句.

 

    情况二:

    int i = 1;
        switch (i) {
            case 0:
                System.out.println("i = 0");
            case 1:
                System.out.println("i = 1");
            case 2:
                System.out.println("i = 2");
            default:
                System.out.println("i 值未确定");
        }

    当不含有 break 时,若 case值 找到,从当前 case 语句开始,返回所有 case 语句, run: i =1 i= 2 i 值未确定.  --- 若为找到,则只执行 default 语句,run: i 值未确定.

 

当判断条件为很多个时,相对 if 语句而言,如果能使用 switch case,更推荐使用switch case语句.

 

下面为使用 enum 的一种方式

public class YoonaLt {
    enum Car {
        Lamborghini(900), Audi(400), Porsche(700);
        private int price;

        Car(int p) {
            price = p;
        }

        int getPrice() {
            return this.price;
        }

    }

    public static void main(String[] args) {
        for (Car c : Car.values()) {
            switch (c.getPrice()) {
                case 900:
                    System.out.println("you choose Lamborghini");
                    break;
                case 400:
                    System.out.println("you choose Audi");
                    break;
                case 700:
                    System.out.println("you choose Porsche");
                    break;
                default:
                    System.out.println("you not choose anyCar");
                    break;
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值