分别用switch语句和if语句实现键盘录入月份,输出对应的季节

本文通过实例对比了Java中使用switch和if语句判断输入月份对应季节的方法。switch适用于固定值判断,代码简洁;if则适合区间判断,逻辑清晰。两种方式均实现了从用户输入到季节输出的转换。

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

  • switch建议判断固定值的时候用
  • if建议判断区间或范围的时候用

1.用switch实现键盘录入月份,输出对应的季节

import java.util.Scanner;
class Hello2 {
    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(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;
        }
    }
}

结果:

2.用if实现键盘录入月份,输出对应的季节

import java.util.Scanner;
class Hello2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入月份");
        int month = sc.nextInt();
        if (month > 12 && month < 1)
        {
            System.out.println("没有对应的季节");
        }else if (month >= 3 && month <=5)
        {
            System.out.println(month + "月是春季");
        }else if (month >=6 && month <=9)
        {
            System.out.println(month + "月是夏季");
        }else if (month >=10 && month <=12)
        {
            System.out.println(month + "月是秋季");
        }else if (month >=1 && month <= 3)
        {
            System.out.println(month + "月是冬季");
        }
            
    }
}

结果:

 

转载于:https://www.cnblogs.com/Wangzui1127/p/11153823.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值