switch分支结构的细节
1.表达式数据类型,应和case 后的常量类型一致,或者是可以自动转成可以相互比较的
类型,比如输入的是字符,而常量是 int
2.switch(表达式)中表达式的返回值必须是:(byte,short,int,char,enum[枚举],String)
3.case子句中的值必须是常量,而不能是变量
4.default子句是可选的,当没有匹配的case时,执行default
5.break语句用来在执行完一个case分支后使程序跳出switch语句块;如果没有写break,程序会顺序执行到switch结尾,除非遇到break;
练习:使用 switch 把小写类型的 char 型转为大写(键盘输入)。只转换 a, b, c, d, e. 其它的输出 "other"。
代码及注释解析
import java.util.Scanner;
public class switchdetail {
//编写一个 main 方法
public static void main(String[] args) {
//使用 switch 把小写类型的
//char 型转为大写(键盘输入)。只转换 a->A, b->B, c, d, e.
//其它的输出 "other"。
//创建 Scanner 对象
Scanner myScanner = new Scanner(System.in);
System.out.println("请输入 a-e");
char c1 = myScanner.next().charAt(0);
switch(c1) {
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("你的输入有误~");
}
}
}