知識點解析
1.switch結構的核心概念
switch語句是一種多分支選擇結構,它根據表達式的值來選擇執行不同的代碼塊。與if-else結構相比,switch更適合處理離散的、有限個值的比較。
2.switch結構的基本語法
switch (表達式) {case 值1:// 代碼塊1[break;]case 值2:// 代碼塊2[break;]...[default:// 默認代碼塊]
}
3.switch結構的特點
- 表達式類型:可以是
byte
、short
、char
、int
、String
(Java 7+)、枚舉類型。 - case值:必須是常量表達式,且不能重復。
- break語句:用于跳出switch結構,防止"程序穿透"。
- default語句:可選,用于處理所有未匹配的情況。
4. switch結構的執行流程
- 計算表達式的值
- 將表達式的值與每個case值進行比較
- 找到匹配的case后,執行對應的代碼塊
- 如果遇到break語句,則跳出整個switch結構
- 如果沒有匹配的case,則執行default代碼塊(如果有)
5. switch結構的注意事項
- case值必須是常量表達式(final變量或字面量)
- case值不能重復
- break語句是可選的,但通常需要
- default語句是可選的,但建議保留
6.switch與if-else的區別
- switch:適用于離散的、有限個值的比較,代碼更清晰。
- if-else:適用于范圍判斷或復雜條件判斷。
案例解析
案例:基本switch結構
public class SwitchExample1 {public static void main(String[] args) {int day = 3;String dayName;switch (day) {case 1:dayName = "星期一";break;case 2:dayName = "星期二";break;case 3:dayName = "星期三";break;case 4:dayName = "星期四";break;case 5:dayName = "星期五";break;case 6:dayName = "星期六";break;case 7:dayName = "星期日";break;default:dayName = "無效的日期";}System.out.println("今天是:" + dayName);}
}
運行結果
今天是:星期三
代碼解析:
- Java源文件保存為“SwitchExample1.java”。
- 定義變量
day
并賦值為3。 - 使用switch結構根據
day
的值輸出對應的星期名稱。 - 當
day
為3時,匹配case 3
,輸出"星期三"。
案例:switch穿透
public class SwitchFallThrough {public static void main(String[] args) {int number = 2;String result;switch (number) {case 1:case 2:case 3:result = "小數字";break;case 4:case 5:case 6:result = "中數字";break;default:result = "大數字";}System.out.println("數字分類:" + result);}
}
運行結果
數字分類:小數字
代碼解析:
- Java源文件保存為“SwitchFallThrough.java”。
- 定義變量
number
并賦值為2。 - 使用switch結構實現穿透(fall-through),多個case共享同一段代碼。
- 當
number
為2時,匹配case 2
,由于沒有break,繼續執行case 3
的代碼,最終輸出"小數字"。
案例:String類型的switch
import java.util.Scanner;public class StringSwitchExample {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("請輸入顏色(red/green/blue):");String color = scanner.nextLine();switch (color) {case "red":System.out.println("紅色代表熱情");break;case "green":System.out.println("綠色代表生機");break;case "blue":System.out.println("藍色代表寧靜");break;default:System.out.println("未知顏色");}}
}
運行結果
請輸入顏色(red/green/blue):red
紅色代表熱情
代碼解析:
- Java源文件保存為“StringSwitchExample.java”。
- 使用Scanner獲取用戶輸入的顏色字符串。
- 使用String類型的switch結構根據顏色輸出對應的描述。
- 當輸入"green"時,輸出"紅色代表熱情"。
案例:枚舉類型的switch
enum Season {SPRING, SUMMER, AUTUMN, WINTER
}public class EnumSwitchExample {public static void main(String[] args) {Season currentSeason = Season.SUMMER;String description;switch (currentSeason) {case SPRING:description = "萬物復蘇";break;case SUMMER:description = "烈日炎炎";break;case AUTUMN:description = "碩果累累";break;case WINTER:description = "白雪皚皚";break;default:description = "未知季節";}System.out.println(&#