class Test{
public static void main(String[] args) {
int i = 9;
switch (i){
default:
System.out.println("default");
case 0:
System.out.println("zero");
case 1:
System.out.println("one");
case 2:
System.out.println("two");
}
}
}
default
zero
one
two
switch语句将表达式的值与每个case中的目标值进行匹配,如果找到了匹配的值,就会执行对应case后的语句;如果没有找到任何匹配的值,就会执行default后的语句,如果switch语句中没有default,则case语句统统不执行。default让我想起了异常与捕获中finally语句的作用,不管default放在switch语句的什么位置,程序在运行的过程中,default后面的语句统统都会执行,除非遇到break。
switch(数字|枚举|字符|字符串){
case 内容1:{
内容满足时执行语句;
[break;]
}
case 内容2:{
内容满足时执行语句;
[break;]
}
……
default:{
内容都不满足时执行语句;
[break;]
}
}
public class Test{
public static void main(String[] args) throws IOException {
System.out.println("请输入字符:");
char c = (char)System.in.read();
switch (c){
case 'a':{
System.out.println("lt takes lots of tactical moves in order to win a game of chess");
}
case 'b':
System.out.println("They sent an assassin to kill me");
default:
System.out.println("My meditation practice relaxes me and calms my mind");
}
}
}
当输入a时,执行结果为:
lt takes lots of tactical moves in order to win a game of chess
They sent an assassin to kill me
My meditation practice relaxes me and calms my mind
当输入d时,执行结果为:
My meditation practice relaxes me and calms my mind