关于switch语句的一点介绍

switch语句是利用选择器的数值来选择符合条件的执行语句,选择器所产生的值必须为整数。一般char类型的数据会转换为整数(promote),string或者其他类型则不能执行这种功能,当然枚举类型可以解决这个问题。
switch语句中,每个case语句最有会有break,表示这条case执行到最后。若没有break,程序会一直执行下去直到遇到break为止(可以执行到下一条case中的语句)。

public class TestSwitch {
    public void autoSwitch1(int i){
        switch (i) {
        case 1:
            System.out.println("this is a number lower than 3");
            break;
        case 2:
            System.out.println("this is a number lower than 3");
            break;
        default:
            System.out.println("this encounter the other situation");
            break;
        }
    }

    public void autoSwitch2(int i){
        switch (i) {
        case 1:
            //System.out.println("this is a number lower than 3");
            //break;
        case 2:
            System.out.println("this is a number lower than 3");
            break;
        default:
            System.out.println("this encounter the other situation");
            break;
        }
    }
    public static void main(String[] args) {
        TestSwitch t = new TestSwitch();
        for (int i = 1; i < 4; i++) {
            //t.autoSwitch1(i);
            t.autoSwitch2(i);
        }
    }

}

运行程序可以发现,autoSwitch1和autoSwitch2 分别用这两个方法会产生相同的结果,在autoSwitch2方法中,无论i为1或者2都会执行到“case 2:”下面的语句,switch语句的这种特性可以在编程中得到很多的方便 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值