• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
雨天才无瓜
博客园    首页    新随笔    联系   管理    订阅  订阅

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

  • 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 + "月是冬季");
        }
            
    }
}

结果:

 

posted @ 2019-07-08 21:02  雨天才无瓜  阅读(3337)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3