流程控制语句------if与switch的区别(2-2)

1.总结switch语句和if语句的各自使用场景
*     switch建议判断固定值的时候用
*     if建议判断区间或范围的时候用
2.分别用switch语句和if语句实现下列需求:
        键盘录入月份,输出对应的季节

      一年有四季
        3,4,5春季
        6,7,8夏季
        9,10,11秋季
        12,1,2冬季

switch:

import java.util.Scanner;
class Test3_SwitchIf {
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);	//创建键盘录入对象
		System.out.println("请输入月份");
		int month = sc.nextInt();		//将键盘录入的结果存储在month
		switch (month) {
		case 3:
		case 4:
		case 5:
			System.out.println(month + "月是春季");
		break;
		case 6:
		case 7:
		case 8:
			System.out.println(month + "月是夏季");
		break;
		case 9:
		case 10:
		case 11:
			System.out.println(month + "月是秋季");
		break;
		case 12:
		case 1:
		case 2:
			System.out.println(month + "月是冬季");
		break;
		default:
			System.out.println("对不起没有对应的季节");
		break;
		}

		
	}
}

if:

import java.util.Scanner;
class Test3_SwitchIf {
	public static void main(String[] args) {
		if (month > 12 || month < 1) {
			System.out.println("对不起没有对应的季节");
		}else if (month >= 3 && month <= 5) {
			System.out.println(month + "月是春季");
		}else if (month >= 6 && month <= 8) {
			System.out.println(month + "月是夏季");
		}else if (month >= 9 && month <= 11) {
			System.out.println(month + "月是秋季");
		}else {
			System.out.println(month + "月是冬季");
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值