A:案例演示
分别用switch语句和if语句实现下列需求:
键盘录入月份,输出对应的季节
a:public class MyTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入月份");
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("输入错误");
}
}
}
b:public class MyTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入月份");
int month=sc.nextInt();
if (month==3|month==4|month==5){
System.out.println("春季");
}else if (month>=6&&month<=8){
System.out.println("夏季");
}else if (month==9|month==10|month==11){
System.out.println("秋季");
}else if (month==1|month==2|month==12){
System.out.println("冬季");
}else{
System.out.println("你乱输入了");
}
}
}
B:在做判断的时候,我们有两种选择,if语句和switch语句,那么,我们到底该如何选择使用那种语句呢?
if语句使用场景:
针对结果是boolean类型的判断
针对一个范围的判断
针对几个常量值的判断
switch语句使用场景:
针对几个常量值的判断