打印日历

package com.ys.mxdx;

import java.util.Scanner;

public class MyCalendar {
//1.定义方法判断一个年份是否为闰年
	public boolean isLeapyear(int year) {
		if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
			return true;
		} else {
			return false;
		}
	}

//2.定义一个方法,判断该年份每个月的天数
	public int getDay(int year, int month) {
		switch (month) {
		case 2:
			if (isLeapyear(year)) { //调用方法1直接方法名调用,因为在同一个类,然后都没有static修饰,直接调用。
				return 29;
			} else {
				return 28;
			}

		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;

		case 4:
		case 6:
		case 9:
		case 11:
			return 30;

		default:
			System.out.println("------请输入正常月份-------");
			return 0;
		}

	}

	// 方法3: 求1900年1月1日 -- year年month月之间总天数(不包括year整年 和 month当月)
	public int totalDay(int year, int month) {
		int day = 0;
		for (int i = 1900; i < year; i++) {
			if (isLeapyear(i)) {
				day += 366;
			} else {
				day += 365;
			}
		}
		for (int j = 1; j < month; j++) {
			day += getDay(year, j);
		}
		return day;
	}

	// 方法4:打印日历
	public void printing(int year, int month) {
		System.out.println(year + "年" + month + "月");
		System.out.println("一\t二\t三\t四\t五\t六\t七");
		int count = 0;
		int space = totalDay(year, month) % 7;
		for (int i = 0; i < space; i++) {
			System.out.print(" \t");
			count++;
		}
		for (int j = 1; j <= getDay(year, month); j++) {
			System.out.print(j + "\t");
			count++;
			if ((count) % 7 == 0) {
				System.out.print("\n");
			}
		}

	}

	public static void main(String[] args) {
        //从键盘获得想要打印的年份月份
		Scanner sc = new Scanner(System.in); 
		System.out.println("请输入年份,月份");
		int year = sc.nextInt();
		int month = sc.nextInt();
		
        //最后调用打印方法
		MyCalendar my = new MyCalendar();
		my.printing(year, month);

	}

}
  1.  选择1900,是因为1900是19世纪的最后一年,他的第一天也就是1900年1月1号正好是星期一。方便以上代码3方法的统计天数。
  2. 主要是判断从键盘录入的年月距离1900年有多少天,比如说2018年7月,就要知道2017年距离1900的天数,加上前六个月的天数,然后对7求余,就可以知道前面的空格数
  3. tips:上面调用方法,if (isLeapyear(year)) { }//调用方法1直接方法名调用,因为在同一个类,然后都没有static修饰,直接调用。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值