在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塊。