2 回答

TA貢獻2011條經(jīng)驗 獲得超2個贊
關(guān)于java中switch使用的一些說明
switch(表達式)
{
case 常量表達式1:語句1;
....
case 常量表達式2:語句2;
default:語句;
}
default就是如果沒有符合的case就執(zhí)行它,default并不是必須的.
case后的語句可以不用大括號.
switch語句的判斷條件可以接受int,byte,char,short,不能接受其他類型.
一旦case匹配,就會順序執(zhí)行后面的程序代碼,而不管后面的case是否匹配,直到遇見break,利用這一特性可以讓好幾個case執(zhí)行統(tǒng)一語句.
例如:
switch(x)
{
case 1:
case 2:
case3: System.out.println("haha");
break;
case4: System.out.println("hehe");
}

TA貢獻1873條經(jīng)驗 獲得超9個贊
test case1 :直接執(zhí)行case2;
test case2 :直接執(zhí)行case2,沒有break,順序執(zhí)行,直到default;
test case2 :順序執(zhí)行,直到結(jié)束;
①break用于跳出switch和循環(huán)語句所以無break則繼續(xù)執(zhí)行以后分支;②default后面的case2和case3還執(zhí)行。
因為按一般人習(xí)慣dafault通常放在最后,可以不加break,直接退出switch。但本題放在中間default與其他分支是一樣的,沒有break則繼續(xù)執(zhí)行。
switch(i)
{ case 1:System.out.println("you are the first!");
case 2:System.out.println("you are the second!");
case 3:System.out.println("you are the third!"); break;
default:System.out.println("you are the last!");
}
添加回答
舉報