Java输入一个月份判断春夏秋冬季节中switch与if使用

本文介绍了一种使用Java程序判断输入月份所属季节的方法。通过if语句和switch语句两种方式实现,展示了基本的条件判断逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们定义3、4、5月为春天,6、7、8月为夏天,9、10、11月为秋天,12、1、2月为冬天。我最先想到的是用if语句:
public class test1 {
    public static void main(String[] args) {
    int mo=3;    //要判断的月份
    if (mo>=3 && mo<=5){
            System.out.println(mo+"月份是春季");
    }else if(mo>=6 && mo<=8){
        System.out.println(mo+"月份是夏季");
    }else if(mo>=9 && mo<=11){
        System.out.println(mo+"月份是秋季");
    }else{
        System.out.println(mo+"月份是冬季");
    }
    }
}

同样可以利用switch的穿透性来判断季节:

public class test1 {
    public static void main(String[] args) {
        int i=3;      //要判断的月份
        switch (i){
            case 3: case 4: case 5:        //switch的穿透性
                System.out.println("春天");
                break;
            case 6: case 7: case 8:
                System.out.println("夏天");
                break;
            case 9: case 10: case 11:
                System.out.println("秋天");
            case 12: case 1: case 2:
                System.out.println("冬天");
                default
                    break;
        }
    }
}
这里运用了switch的穿透性,即一个case中没有break结束的话会一直执行下去
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值