Switch分支结构细节
细节一
- 表达式数据类型,应和case后的常量类型一致
- 或者是可以自动转成可以相互比较的类型,比如输入的是字符,而常量是int
char c = 'c';
switch (c){
case 'a':
System.out.println("ok1");
break;
case 'b':
System.out.println("ok2");
break;
default:
System.out.println("default");
}
细节二
- switch(表达式)中表达式的返回值必须是byte, short, int, char, enum,String
细节三
- case字句中的值必须是常量,或者是常量表达式,而不能是变量。
char c = 'a';
char c2 = 'h';
switch (c){
case 'a':
System.out.println("ok1");
break;
case 'b'+1://常量表达式,正确
System.out.println("ok1");
break;
case c2: //报错。不能用变量
System.out.println("ok2");
break;
default:
System.out.println("default");
}
细节四
- default字句是可选的,当没有匹配的case时,执行default
- 如果没有default字句,又没有匹配任何常量,则没有输出
细节五
- break语句用来执行完一个case分支后使程序跳出switch语句块
- 如果没有写break,程序会顺序执行到switch结尾,除非执行到break
char c = 'a';
switch (c){
case 'a':
System.out.println("ok1");
//break;
case 'b':
System.out.println("ok2");
break;
default:
System.out.println("default");
}
/* 输出结果为
ok1
ok2
*/
switch练习
- 使用switch把小写类型的char转为大写(键盘输入)。只转换a,b,c,d,e其他输出other
Scanner sc = new Scanner(System.in);
System.out.println("请输入a-e");
char c = sc.next().charAt(0);
switch (c){
case 'a':
System.out.println("A");
break;
case 'b':
System.out.println("B");
break;
case 'c':
System.out.println("C");
break;
case 'd':
System.out.println("D");
break;
case 'e':
System.out.println("E");
break;
default:
System.out.println("other");
}
- 对学生成绩大于60分的,输出合格。低于60分的输出不合格(注:成绩不能大于100)
- 如果成绩在[60,100],(int)(成绩/60)=1 //60以上除以60 的1.多 都会经过强转变成1
- 如果成绩在[0,60), (int)(成绩/60)=0
//如果成绩在[60,100],(int)(成绩/60)=1
//如果成绩在[0,60), (int)(成绩/60)=0
Scanner sc = new Scanner(System.in);
double score = sc.nextDouble();
if(score>=0 && score <= 100){
int a = (int)(score/60);
switch (a) {
case 0:
System.out.println("不及格");
break;
case 1:
System.out.println("及格");
break;
// default:
// System.out.println("输入有误");
}
}else{
System.out.println("输入成绩要在0-100");
}
- 根据用于指定月份,打印该月份所属的季节。345春季,456夏季,9,10,11秋季,12,1,2冬季
提示使用穿透
Scanner sc = new Scanner(System.in);
int month = sc.nextInt();
switch (month){
case 3:
case 4:
case 5:
System.out.println("春季");
break;
case 6:
case 7:
case 8:
System.out.println("夏季");
break;
case 9:
case 10:
case 11:
System.out.println("秋季");
break;
case 12:
case 1:
case 2:
System.out.println("冬季");
break;
default:
System.out.println("输入月份不对(1-12)");
}