舉例練習(xí):java switch語句
public?class?Test7?{
?public?static?void?main(String[]?args)
?{
??int?i=5;
??switch(i)
??{
??
??case?1:
???System.out.println("one");
???
??case?10:
???System.out.println("ten");
???
??case?5:
???System.out.println("five");
???
??case?3:
???System.out.println("three");
???
??default:
???System.out.println("other");
??}
?}
}
為什么結(jié)果是:
five
three
other
而沒有one和ten,這是為什么呢?
switch(表達(dá)式)
{
case?常量表達(dá)式1:語句1;
....
case?常量表達(dá)式2:語句2;
default:語句;
}
switch的用法是判斷case后面的表達(dá)式和switch后面的表達(dá)式是否相匹配,一旦case匹配,就會(huì)順序執(zhí)行后面的程序代碼,而不管后面的case是否匹配,直到遇見break。
在你所給的代碼中,由于i等于5,和前面的兩個(gè)case都不匹配,所以結(jié)果中并沒有one和ten的。而第三個(gè)case中的5就和switch中i的值匹配,因此就會(huì)打印出five的,由于沒有遇到break所以就會(huì)順序執(zhí)行很面的代碼,打印出three和other