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语句的这种特性可以在编程中得到很多的方便 。