switch分支结构
格式
switch(表达式)
{
case 常量1: //当表达式的值等于常量1,就执行语句块1
语句块1;
break; //表示退出switch结构,若没有break,则穿透到语句块2,并执行下去,直到break退出
case 常量2:
语句块2;
break;
…………
case 常量n:
语句块n;
break;
default: //如果上面都没匹配上,则执行default
default 语句块;
break;
}
注意
-
表达式数据类型,应和case后的数据类型一样,
或者可以自动转换可以相互比较类型的,比如输入的是字符,而常量是int
-
switch(表达式)中的表达式的返回值必须是:(byte,short,int,char,String,enum[枚举])
-
case 子句中的值必须是常量,而不能是变量
-
default 子句是可选的,当没有匹配的case时,执行default
-
break语句是用来帮助一个case分支跳出switch语句,如果没写break,则会穿透执行下一个case中的语句块,一直执行下去,直到出现break/执行完default语句也自动跳出
switch(a)//首先表达式满足 byte,short,int,char,enum[枚举],String六个其中之一
{
case 50 : //也是可以的,字符a会自动转换为97
System.out.println("");
break;
case 'd'+1 : //也行,结果还是常量,且数据类型和switch中的一致
System.out.println("");
break;
default : //可以没有
System.out.println("");
举例
//接收一个字符(a-g),分别代表抽奖礼品
import java.util.Scanner;
public class text
{
public static void main (String[] args)
{
Scanner scanner= new Scanner(System.in);
System.out.println("请输入一个字符【a-g】");
char letter = scanner.next().charAt(0);
switch(letter)
{
case 'a' :
System.out.println("中了一等奖");
break;
case 'd' :
System.out.println("中了二等奖");
break;
case 'g' :
System.out.println("中了三等奖");
break;
default :
System.out.println("纪念奖");
}
}
}
//使用switch 打印月份的季节
import java.util.Scanner;
public class text
{
public static void main (String[] args)
{
Scanner scanner= new Scanner(System.in);
int mounth = scanner.nextInt();
switch (mounth)
{
case 3:
case 4:
case 5:
System.out.println("春季");
break;
case 12:
case 1:
case 2:
System.out.println("冬季");
break;
case 6:
case 7:
case 8:
System.out.println("夏季");
break;
case 9:
case 10:
case 11:
System.out.println("秋季");
break;
default :
System.out.println("你输入的有误");
}
}
}
switch与if的比较
- 如果判断的具体数值不多,而且符合(byte,short,int,char,enum[枚举],String这六大类型),建议使用switch
- 对于区间判断,对结果为boolean类型判断,使用if的范围更广
.