大家好,又见面了,我是你们的朋友全栈君。
switch 语句由一个控制表达式和多个case标签组成。
switch 控制表达式支持的类型有byte、short、char、int、enum(Java 5)、String(Java 7)。
switch-case语句完全可以与if-else语句互转,但通常来说,switch-case语句执行效率要高。
default在当前switch找不到匹配的case时执行。default并不是必须的。
一旦case匹配,就会顺序执行后面的程序代码,而不管后面的case是否匹配,直到遇见break。
| |目录
1语法格式
|
1
2
3
4
5
6
7
8
9
10
11
|
switch (表达式) {
case 条件1:
语句1;
break;
case 条件2:
语句2;
break;
...
default:
语句;
}
|
2使用示例
int类型switch示例
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
int i = 3;
switch (i) {
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
default:
System.out.println(0);
}
|
枚举(Enum)类型switch示例
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package net.xsoftlab.baike;
public class TestSwitch {
static enum E {
A, B, C, D
}
public static void main(String args[]) {
E e = E.B;
switch (e) {
case A:
System.out.println("A");
break;
case B:
System.out.println("B");
break;
case C:
System.out.println("C");
break;
case D:
System.out.println("D");
break;
default:
System.out.println(0);
}
}
}
|
String类型switch示例
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
String str = "C";
switch (str) {
case "A":
System.out.println("A");
break;
case "B":
System.out.println("B");
break;
case "C":
System.out.println("C");
break;
default:
System.out.println(0);
}
|
3break
break在switch中用于结束当前流程。
一旦case匹配,就会顺序执行后面的程序代码,而不管后面的case是否匹配,直到遇见break。
忘记写break的陷阱
示例:
|
1
2
3
4
5
6
7
8
9
10
11
|
int i = 2;
switch (i) {
case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
default:
System.out.println(0);
}
|
输出结果:
|
1
2
3
|
2
3
0
|
巧用break
实例:输出2015年指定月份的最大天数
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
int year = 2015;
int month = 8;
int day = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = 31;
break;
case 2:
day = 28;
break;
case 4:
case 6:
case 9:
case 11:
day = 30;
break;
}
System.out.println(day);
|
4default
default在当前switch找不到匹配的case时执行。default并不是必须的。
示例:
|
1
2
3
4
5
6
7
8
9
|
int x = 0;
switch (x) {
case 1:
System.out.println(1);
case 2:
System.out.println(2);
default:
System.out.println("default");
}
|
输出结果:
|
1
|
default
|
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/154345.html原文链接:https://javaforall.net
