在Java中,switch語句有三種常見的用法方式:
int num = 1;
switch (num) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Other");
}
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("Today is Monday");
break;
case TUESDAY:
System.out.println("Today is Tuesday");
break;
default:
System.out.println("Other day");
}
String str = "Java";
switch (str) {
case "Java":
System.out.println("Java programming language");
break;
case "Python":
System.out.println("Python programming language");
break;
default:
System.out.println("Other programming language");
}
需要注意的是,上述每種用法都需要在每個case語句末尾加上break
語句,以避免執行其他case語句。如果沒有匹配的case語句,可以使用default
語句來執行默認操作。