用程序打印万年历

//1900年到输入的年份当月的日历

import java.util.Scanner;

public class CalendarMethod {
     
    public static void main(String[] args) {
        
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入年份:");
        int year = scan.nextInt();
        System.out.println("请输入月份:");
        int month = scan.nextInt();
        
        printCalendar(year,month);

    }
    
    public static void printCalendar(int year,int month){
        
        int totalDays = getTotalDays(year,month);
        
        int temp = (totalDays + 1) % 7;
        
        System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
        for(int i=1; i<=temp; i++){
            System.out.print("\t");
        }
        
        for(int i=1; i<=getMonthDay(year,month); i++){
            System.out.print(i + "\t");
            if( (totalDays + i + 1) % 7 == 0){
                System.out.println();
            }
        }
        
    }
    
    //获取总天数
    public static int getTotalDays(int year,int month){
        
        int totalYearDays = getTotalYearDays(year);
        int totalMonthDays = getTotalMonthDays(year,month);
        
        int totalDays = totalYearDays + totalMonthDays;
        
        return totalDays;
    }

    //获取制定年份月份之前的月份的总天数
    private static int getTotalMonthDays(int year, int month) {
        int totalMonthDays = 0;
        
        for(int i=1; i<month; i++){
            totalMonthDays += getMonthDay(year,i);
        }
        
        return totalMonthDays;
    }
    
    //获得你传入年份月份的天数
    public static int getMonthDay(int year,int month){
        boolean isRN = isRN(year);
        int monthDay = 0;
        switch(month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                monthDay = 31;
                break;
            case 2:
                if(isRN) monthDay = 29;
                else monthDay = 28;
                break;
            default:
                monthDay = 30;
                break;
        }
        
        return monthDay;
    }

    //得到年份總天數的方法
    public static int getTotalYearDays(int year) {
        // 计算1900年至你输入的年份位置的总天数
        int totalYearDays = 0;
        for (int i = 1900; i < year; i++) {
            if (isRN(i)) {
                totalYearDays += 366;
            } else {
                totalYearDays += 365;
            }
        }
        return totalYearDays;
    }
    
    public static boolean isRN(int year){
        boolean isRN = false;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            isRN = true;
        }
        return isRN;
    }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值