用來判定所給定的條件是否滿足,根據(jù)判定的結果(真或假)決定執(zhí)行哪個操作
定義:
switch(<key>){ case <value-1>: statements-1; break; case <value-2>: statements-2; break; default: statements-3; break; } //執(zhí)行順序:當key值和value-1的值一樣時,執(zhí)行statements-1并結束;如果key和value-1值不等,但等于value-2時,執(zhí)行statements-2并結束;...;如果都不相等,則執(zhí)行statements-3并結束
注:1、case語句可以存在多個;
2、可以沒有default語句,但為防止因未在case語句中匹配到與key值相等的value報錯,盡量存在一個(最多一個)default語句;
3、在每個case和default語句后可以沒有break;語句,表示不結束switch語句,繼續(xù)執(zhí)行,如在上例中沒有break語句,假設key和value-2相等,則在執(zhí)行完statements-2后會再執(zhí)行statements-3
舉例:
Integer = 3 switch (day) { case 0: x="Today it's Sunday"; break; case 1: x="Today it's Monday"; break; case 2: x="Today it's Tuesday"; break; case 3: x="Today it's Wednesday"; break; case 4: x="Today it's Thursday"; break; case 5: x="Today it's Friday"; break; case 6: x="Today it's Saturday"; break; }//最終結果 Today it's Wednesday