在Java中,switch语句用于根据一个表达式的值在一组可能的选项中选择执行的代码块。以下是switch语句的一些用法:
int num = 2;
switch (num) {
case 1:
System.out.println("Number is 1");
break;
case 2:
System.out.println("Number is 2");
break;
default:
System.out.println("Number is not 1 or 2");
break;
}
int num = 2;
switch (num) {
case 1:
case 2:
System.out.println("Number is either 1 or 2");
break;
default:
System.out.println("Number is neither 1 nor 2");
break;
}
String day = "Monday";
switch (day) {
case "Monday":
System.out.println("It's Monday");
break;
case "Tuesday":
System.out.println("It's Tuesday");
break;
default:
System.out.println("It's neither Monday nor Tuesday");
break;
}
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day day = Day.MONDAY;
switch (day) {
case MONDAY:
System.out.println("It's Monday");
break;
case TUESDAY:
System.out.println("It's Tuesday");
break;
default:
System.out.println("It's neither Monday nor Tuesday");
break;
}
需要注意的是,每个case语句后面要跟着一个break语句,用于结束switch块。如果没有break语句,程序将会继续执行下一个case中的代码。如果没有匹配到任何一个case,将会执行default块中的代码(如果有)或者直接退出switch块。