运算符和表达式 、 分支结构 输入年份和月份,输出该月的天数(使用switch-case)

思路:三个板块,A.二月比较特殊,平年的二月只有28天,而闰年的二月有 29 天;

        B.4、6、9、11月;

        C.其他1、3、5、7、8、10、12月。

 

import java.util.Scanner;
public class DayOfMonth {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入年份(例如:2012)");
        int year = scanner.nextInt();
        System.out.println("请输入月份(例如:1)");
        int month = scanner.nextInt();
        scanner.close();
        // 某月的天数
        int days = 0;
        switch (month) {
        case 2:
            // 判断是否为闰年,闰年29天,非闰年28天
            if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
                days = 29;
            } else {
                days = 28;
            }
            break;
        // 4,6,9,11为小月
        case 4:
        case 6:
        case 9:
        case 11:
            days = 30;
            break;
        // 其余为大月
        default:
            days = 31;
        }
        System.out.println(year + "年" + month + "月有" + days + "天");
    }
}

 

posted on 2016-09-04 22:08  luckyBrown  阅读(5846)  评论(0编辑  收藏  举报