switch中default的用法
生活随笔
收集整理的這篇文章主要介紹了
switch中default的用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
default什么時候會執行?default的位置對執行結果有影響嗎?
default只有在case匹配失敗的時候才會執行
int a=4;switch (a){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("default");break;打印結果:default
當然也有特殊情況,就是case匹配成功了,但缺少了break語句
int a=3;switch (a){case 1:System.out.println("1");break;case 2:System.out.println("2");break;case 3:System.out.println("3");default:System.out.println("default");break;打印結果:
3
default
default的位置對執行結果有沒有影響,關鍵看default有沒有使用break,先看有break的情況下是什么結果
int a=4;switch (a){default:System.out.println("default");break;case 1:System.out.println("1");break;case 2:System.out.println("2");break;case 3:System.out.println("3");break;}打印結果:default
接下來看看不加break是什么結果
int a=4;switch (a){default:System.out.println("default");case 1:System.out.println("1");case 2:System.out.println("2");break;case 3:System.out.println("3");break;}打印結果:
default
1
2
可以看到不加break的話會繼續向下執行,直到遇到break或return或switch結束為止
總結
以上是生活随笔為你收集整理的switch中default的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浏览器和搜索引擎的区别
- 下一篇: 文件属性常数