switch语法中break,default作用说明
轉自:http://cjhbest999.iteye.com/blog/1137124
關于java中switch使用的一些說明
switch(表達式)
{
case 常量表達式1:語句1;
....
case 常量表達式2:語句2;
default:語句;
}
default就是如果沒有符合的case就執行它,default并不是必須的.
case后的語句可以不用大括號.
switch語句的判斷條件可以接受int,byte,char,short,不能接受其他類型.
如果使用long類型的話編譯時會有錯誤產生,這點在使用上要注意,其他的數據類型都不行。
簡單地說就是能夠自動轉換程int類型的數據類型才行。
而case是指switch小括號中的變量會出現且你想要處理的值,它除了可以是個整數、字符之外,還可以是一些簡單的算術表達式,不過算數表達式的結果要滿足剛剛所說的四種數據類型。一旦case匹配,就會順序執行后面的程序代碼,而不管后面的case是否匹配,直到遇見break,利用這一特性可以讓好幾個case執行統一語句
Java代碼
1.packageflowcontrol;
2.
3.publicclassSwitchCase{
4.//firstdefault
5.publicstaticvoidtestFirst(inti){
6.switch(i){
7.default:
8.System.out.println("default");//firstdefault
9.case1:
10.System.out.println("one");
11.case2:
12.System.out.println("two");
13.case3:
14.System.out.println("there");
15.}
16.}
17.
18.//lastdefault
19.publicstaticvoidtestLast(inti){
20.switch(i){
21.case1:
22.System.out.println("one");
23.case2:
24.System.out.println("two");
25.case3:
26.System.out.println("there");
27.default:
28.System.out.println("default");//lastdefault
29.}
30.}
31.
32.//middledefault
33.publicstaticvoidtestMiddle(inti){
34.switch(i){
35.case1:
36.System.out.println("one");
37.case2:
38.System.out.println("two");
39.default:
40.System.out.println("default");//middledefault
41.case3:
42.System.out.println("there");
43.
44.}
45.}
46.
47.publicstaticvoidmain(String[]args){
48.//firstdefault
49.testFirst(2);
50.System.out.println("------------------");
51.testFirst(9);
52.
53.System.out.println("|||||||||||||||||||||||||||||||||||");
54.
55.//lastdefault
56.testLast(2);
57.System.out.println("----------------");
58.testLast(9);
59.
60.System.out.println("|||||||||||||||||||||||||||||||||||");
61.//middledefault
62.testMiddle(2);
63.System.out.println("----------------");
64.testMiddle(9);
65.
66.}
67.
68.}
輸入結果:
Java代碼
1.two
2.there
3.------------------
4.default
5.one
6.two
7.there
8.|||||||||||||||||||||||||||||||||||
9.two
10.there
11.default
12.----------------
13.default
14.|||||||||||||||||||||||||||||||||||
15.two
16.default
17.there
18.----------------
19.default
20.there
看了結果,可以這樣理解:
(1)switch語句關鍵地方是進入點,有了進入點沒有break的情況下會執行到底
(2)沒有匹配值的時候default就是進入點,進入default以后會和普通進入點一樣,如果沒有break繼續執行下面語句
(3)如果有break 則是從進入點到 break中間的語句執行
總結
以上是生活随笔為你收集整理的switch语法中break,default作用说明的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: maven依赖问题
- 下一篇: 华为与 Hansol PNS 达成合作,