利用Java制作万年历(新手简易版)

#题目要求#

从键盘输入年份,可直接实现输出当年所有月份月历

#注意事项#

1.借助输入年份判断平闰年得到2月天数

2.精准保证每个月天数正确

3.每个月起始星期数和日历相同

4.新手上机,希望大佬们多多指正修改

#代码#

1.创建MyCalendar类,定义类中拥有两个属性为year和month

public class MyCalendar {

	private int year;
	private int month;

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

2.创建成员方法calendar,利用该方法计算每个月的天数,起始星期数(获取每月天数也可以用getActualMaximum(Calendar.DAY_OF_MONTH)来实现,图片中方式更加倾向于像我一样的新手)

结尾出现的create函数也是自己构建的,在下一部分

//利用方法计算每个月日历
	public void calendar(int year, int month) {
		// 格式化日历
		Calendar calendar = Calendar.getInstance();
		// 设置日期,月份从0开始计数
		calendar.set(year, month - 1, 1);
		// 获取每个月的天数
		int dayOfMonth = 0;
		switch (month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			dayOfMonth = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			dayOfMonth = 30;
			break;
		case 2:
			if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
				dayOfMonth = 29;
			} else
				dayOfMonth = 28;
			break;
		default:
			break;
		}
		// 获取某一个月份的第一天是该周的第几天(周几需要用fristDay-1)
		int fristDay = calendar.get(Calendar.DAY_OF_WEEK);
		// 定义一个数组,表示每个月的月历,长度为该月份的天数+第一天前面的空白
		int[] nums = new int[dayOfMonth + fristDay - 1];
		// 利用循环给数组赋值,起点为第一天的星期数
		int date=1;
		for (int i = fristDay - 1; i < nums.length; i++) {
			nums[i] = date;
			date++;
		}
		// 利用create制作月历
		create(nums);
	}

3.构建create成员方法,利用for循环语句进行月历格式的编撰

// 利用循环绘制月历

	public void create(int[] nums) {
		for (int i = 0; i < nums.length; i++) {
			// 月历前面的空格未赋值,在int型中为0,所以遇到0则输出空格
			if (nums[i] == 0) {
				System.out.print("\t");
			} else {
				System.out.print(nums[i] + "\t");
			}
			// 一周七天放一行
			if (i % 7 == 0) {
				System.out.println("\n");
			}
		}
		System.out.println("\n");

4.主函数

从键盘输入年份,利用for循环语句不断地向其中输入月份

public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入年份");
		int year = sc.nextInt();
		System.out.println(year+"的年历为");
		for(int i=1;i<=12;i++) {
			MyCalendar calendar=new MyCalendar();
			System.out.println(year+"年"+i+"月");
			System.out.println("一\t二\t三\t四\t五\t六\t日\t");
			calendar.calendar(year, i);
		}
	}

#代码实现#

以2024年为例,创建输出万年历

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值