Java switch多值匹配操作詳解
這篇文章主要介紹了Java switch多值匹配操作詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
我們都知道 switch 用來走流程分支,大多情況下用來匹配單個值,如下面的例子所示:
/** * @author 棧長 */ private static void test(int value) { switch (value) { case 1: System.out.println("1"); break; case 2: System.out.println("1"); break; case 3: System.out.println("1"); break; case 4: System.out.println("1"); break; case 5: System.out.println("1"); break; case 6: System.out.println("0"); break; case 7: System.out.println("0"); break; default: System.out.println("-1"); } }
相關(guān)閱讀:switch case數(shù)據(jù)類型。
大概的意思就是,周一到周五輸出:1,周六到周日輸出:0,默認(rèn)輸出-1。
這樣寫,很多重復(fù)的邏輯,冗余了。
也許這個例子不是很合適,用 if/ else 更恰當(dāng),但這只是個例子,實際開發(fā)中肯定會有某幾個 case 匹配同一段邏輯的情況。
那么,如何讓多個 case 匹配同一段邏輯呢?
如下面例子所示:
/** * @author 棧長 */ private static void test(int value) { switch (value) { case 1: case 2: case 3: case 4: case 5: System.out.println("1"); break; case 6: case 7: System.out.println("0"); break; default: System.out.println("-1"); } }
把相同邏輯的 case 放一起,最后一個 case 寫邏輯就行了。
格式化后就是這樣了:
/** * @author 棧長 */ private static void test(int value) { switch (value) { case 1: case 2: case 3: case 4: case 5: System.out.println("1"); break; case 6: case 7: System.out.println("0"); break; default: System.out.println("-1"); } }
是不是很騷?
其實這不是最合適的最好的寫法,在 Java 12 中還可以更騷。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot druid數(shù)據(jù)庫連接池連接失敗后一直重連的解決方法
本文主要介紹了springboot druid數(shù)據(jù)庫連接池連接失敗后一直重連的解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04springboot中使用@Transactional注解事物不生效的坑
這篇文章主要介紹了springboot中使用@Transactional注解事物不生效的原因,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01mybatis-plus報錯net.sf.jsqlparser.statement.select.SelectBody的
本文主要介紹了mybatis-plus報錯net.sf.jsqlparser.statement.select.SelectBody的問題解決,具有一定的參考價值,感興趣的可以了解一下2024-08-08Mybatis接口Mapper內(nèi)的方法為啥不能重載嗎
這篇文章主要介紹了Mybatis接口Mapper內(nèi)的方法為啥不能重載嗎,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09方法參數(shù)屬性params,@PathVariable和@RequestParam用法及區(qū)別
這篇文章主要介紹了方法參數(shù)屬性params,@PathVariable和@RequestParam用法及區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-10-10