java实现万年历

万年历

  1. 分析
    练习程序分析和逻辑
    输入年 打印该年12个月的所有日历
    输入的年 区分闰年和平年
    确定每个月有多少天
    如何确定每个月的1号是周几
    一 二 三 四 五 六
    时间的计算方式,所有的计算机都是1900开始计算
    1900 1月1号 周1 31天
    2月1号 周4 28天 31%7 = 3 +1 =周四4
    3月1号 周4 31天 (28 + 31)% 7 = 3 + 1 = 周4
    4月1号 周7 30天 (31 + 28 + 31)% 7 = 6 + 1 = 周7
    5月1号 周2
1901年的 2月1号
(1900所有天+1901年1月天)% 7 +1 = 周几
365+31  = 4 +1 周五
package com.fjh.training;

import java.util.Scanner;

public class Calendar {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入年份:");
		int year = sc.nextInt();
		System.out.println("请输入月份:");
		int month = sc.nextInt();
		//getTotalDays(year);
		//格式化输出日历
		CalendarFormatOutput(year,month);
		
		
		
	}
	/**
	 * 格式化输出日历
	 * @param year
	 * @param moth
	 */
	public static void CalendarFormatOutput(int year,int month){
		int flag = 0;
		//打印日历表头
		System.out.println("星期一\t\t星期二\t\t星期三\t\t星期四\t\t星期五\t\t星期六\t\t星期日");
		for (int j=1;j<weekdays(year, month);j++){
			System.out.print("\t\t");
			flag++;
		}
		for(int i=1;i<=getNowMonthDays(year,month);i++){
			System.out.print(i+"\t\t");
			flag++;
			
			if(flag % 7 == 0){
				System.out.println();
			}
		}	
		
	}
	/**
	 * 判断是否为闰年
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(int year){
		return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);	
	}
	
	/**
	 * 判断当前年份距离1900总天数
	 * @param year
	 * @return
	 */
	public static int getTotalDays(int year){
		int totalDays = 0;
		for(int i = 1900; i< year; i++){//i:年份
			totalDays += isLeapYear(i) ? 366:365;
			
		}
		//System.out.println("总天数为:"+totalDays);
		return totalDays;
	}
	/**
	 * 判断当前月份总天数
	 * @param year
	 * @param month
	 * @return
	 */
	public static int getNowMonthDays(int year,int month){
		switch(month){
			case 2:
				return isLeapYear(year) ? 29 : 28;
			case 4:
				return 30;
			case 6:
				return 30;
			case 9:
				return 30;
			case 11:
				return 30;
			default:
				return 31;
		}
	}
	public static int getTotaldayThisYear(int year,int month){
		int totaldaythisyear=0;
		for(int i=1;i< month;i++){
			totaldaythisyear += getNowMonthDays(year,i);
		}
		return totaldaythisyear;
	}
	/**
	 * 获取当月第一天星期几
	 * @param year
	 * @param month
	 * @return
	 */
	public static int weekdays(int year,int month){
		int weekdays = 0;
		weekdays = (getTotalDays(year)+(getTotaldayThisYear(year,month))+1)%7;
		return weekdays;
	}
	
}

输出结果
在这里插入图片描述

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值