控制语句
选择结构
- if , if…else
- switch
循环结构
- for
- while
- do…while
控制循环
- break
- continu
本篇学习的是switch
switch属于选择也属于分支语句
switch(){ //int或string类型的字面量或变量
case //int或string类型的字面量或变量:
//语句
...
break;
case //int或string类型的字面量或变量:
//语句
...
break;
...
default:
//语句
}
- switch括号里的值与case后的值进行匹配, 对应则执行相应分支的语句, 匹配顺序为从上到下.
- 匹配成功后, 若执行的分支语句中有 “break;” 则终止switch语句
- 若没有 “break;” 语句,则直接进入下一分支执行语句(无论是否匹配,直到遇见break或者执行完其后的所有分支), 该现象被称为case穿透现象.
- 如果所有分支都没有匹配成功,则执行default中的语句
- switch括号内只能是int类型(jdk1.6)或者string类型(jdk1.7及以上), 不支持其他类型, 当然byte,short,char也能写在switch或case之后, 因为能自动转换.
(byte < short < int < long < float < double) - switch 中的case 可以合并
`int 1-5
switch(){
case 1: case 2: case 3:
//语句
break;
case 4: case 5: case 6:
…
} - 如果要传long, float, double类型的值时,要注意强制类型转换
double i = 3.4;
switch((int)i){...}//进行强制类型转换,高精度到低精度
简单的例子
import java.util.Scanner;
public class switchTest {
public static void main(String arg[]) {
Scanner s = new Scanner(System.in);
int num = s.nextInt();
switch(num){
case 1 :
System.out.print("今天星期一");
break;
case 2 :
System.out.print("今天星期二");
break;
case 3 :
System.out.print("今天星期三");
break;
case 4 :
System.out.print("今天星期四");
break;
case 5 :
System.out.print("今天星期五");
break;
case 6 :
System.out.print("今天星期六");
break;
case 7 :
System.out.print("今天星期天");
break;
default :
System.out.print("输入不合法");
}
}
}