每个case最好都写上break;因为匹配到一个case的时候如果没有break,会继续执行下面没有被匹配的case,直到遇到break或者代码执行结束
public class LockCondtionDemo1 {
static enum Color{
Red,Green,Yellow,Pink
}
private static void printColor(Color color){
switch (color){
case Red:
System.out.println("red");
case Green:
System.out.println("green");
case Yellow:
System.out.println("yello");
case Pink:
System.out.println("pink");
default:
System.out.println("default");
}
}
public static void main(String[] args) {
printColor(Color.Green);
}
}
执行结果
green
yello
pink
default
如果加上break
public class LockCondtionDemo1 {
static enum Color{
Red,Green,Yellow,Pink,Other
}
private static void printColor(Color color){
switch (color){
case Red:
System.out.println("red");break;
case Green:
System.out.println("green");break;
case Yellow:
System.out.println("yello");break;
case Pink:
System.out.println("pink");break;
default:
System.out.println("default");break;
}
}
public static void main(String[] args) {
printColor(Color.Green);
}
}
输出结果:
····
green
····
网友评论