您的位置:首页 > 编程语言 > Java开发

关于switch语句的一点介绍

2015-08-04 11:21 447 查看
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语句的这种特性可以在编程中得到很多的方便 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java switch