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

结果:

原文地址:https://www.cnblogs.com/Wangzui1127/p/11153823.html