📅  最后修改于: 2023-12-03 15:01:32.606000             🧑  作者: Mango
Java中的Switch语句是一种“多路分支”语句,可以根据变量的值跳转到相应的代码块。在一定程度上,它可以取代一系列的if-else语句,使代码更加简洁和易读。
Switch语句的语法如下:
switch (variable) {
case value1:
// code to be executed if variable == value1
break;
case value2:
// code to be executed if variable == value2
break;
// more cases are possible
default:
// code to be executed if variable doesn't match any cases
}
其中:
每个 case 后面必须带有 break 语句,用于跳出 switch 结构,如果没有 break 会执行后续 case 中的代码块。
int dayOfWeek = 5;
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println(dayName); // Output: Friday
该示例根据变量 dayOfWeek 的值(5)输出星期五的名称。
在某些情况下,Switch语句可以替代多个If-else语句,让代码更加简洁、易读,举个例子:
public void printNumberInText(int number) {
if (number == 1) {
System.out.println("One");
} else if (number == 2) {
System.out.println("Two");
} else if (number == 3) {
System.out.println("Three");
} else if (number == 4) {
System.out.println("Four");
} else if (number == 5) {
System.out.println("Five");
} else {
System.out.println("Unknown Number");
}
}
可以使用Switch语句,让代码更加优雅:
public void printNumberInText(int number) {
switch (number) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
break;
default:
System.out.println("Unknown Number");
break;
}
}