Day03_SHJavaTraining_4-5-2017
switch注意事項:
①switch語句接受的數據類型
switch語句中的表達式的數據類型,是有要求的
JDK1.0 - 1.4?? ?數據類型接受 byte short int char
JDK1.5?? ??? ???? 數據類型接受 byte short int char enum(枚舉)
JDK1.7?? ??? ???? 數據類型接受 byte short int char enum(枚舉), String
②case穿透
在使用switch語句的過程中,如果多個case條件后面的執行語句是一樣的,則該執行語句只需書寫一次即可,這是一種簡寫的方式。
1 /** 2 例如:要判斷一周中的某一天是否為工作日,同樣使用數字1~7來表示星期一到星期天, 當輸入的數字為1、2、3、4、5時就視為工作日,否則就視為休息日。 3 */ 4 int day = (new Scanner(System.in)).nextInt();//從鍵盤輸入某一天的值 5 switch(day){ 6 case 1: 7 case 2: 8 case 3: 9 case 4: 10 case 5: 11 System.out.println("該天為工作日"); 12 break; 13 default: 14 System.out.println("該天為休息日"); 15 break; 16 }
③default關鍵字是可選的(可有可無),而且它的位置是隨意的;但是在實際開發中,一般default會被書寫在整個switch結構的最后。
④default一定是最后才會被jvm執行的。
int num = 3; num = 10;switch(num){case 0:System.out.println("zero");case 1:System.out.println("one");default:System.out.println("此代碼最后執行");case 2:System.out.println("two");case 3:System.out.println("three");break;}