在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
语句来执行默认操作。