Java编写万年历

作者:小小谷 | 创建时间: 2023-07-17
万年历(gregorian solar calendar and chinese lunar calendar)我国古代传说中最古老的一部太阳历。为纪念历法编撰者万年功绩,便将这部历法命名为“万年历”。而现在所使用的万年历,实际上就是记录一...
Java编写万年历

操作方法

首先打开eclipse

新建一个java项目,名字随意起

名字起好后,点击完成

右键点击项目名称,新建,类

类的名字叫TextControl 包的名字叫 com.zf.s2 点击完成

创建一个包。导入输入输出流类 package com.zf.s2;//创建一个包 import java.io.*;

操作打印任一年日历的类 public class TextControl{ static int year, monthDay, weekDay; // 定义静态变量,以便其它类调用 public static boolean isLeapYear(int y) {// 判断是否是闰年 return ((y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)); } public static int firstDay(int y) {// 计算该年第一天是星期几 long n = y * 365; for (int i = 1; i < y; i++) if (isLeapYear(i))// 判断是否是闰年 n += 1; return (int) n % 7; }

打印标题 public static void printWeek(){// 打印标头 System.out.println("==========================="); System.out.println("日  一  二  三  四  五  六"); }

获取每个月的天数 public static int getMonthDay(int m){ switch (m) { 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; case 2: if (isLeapYear(year))// 判断是否是闰年 return 29; else return 28; default: return 0; } }

分别按不同条件逐月打印 public static void printMonth(){ for (int m = 1; m <= 12; m++) // 循环月份 { System.out.println(m + "月"); printWeek(); for (int j = 1; j <= weekDay; j++){// 按每个月第一天是星期几打印相应的空格 System.out.print("    "); } int monthDay = getMonthDay(m); // 获取每个月的天数 for (int d = 1; d <= monthDay; d++) { if (d < 10)// 以下4行对输出格式化 System.out.print(d + "   "); else System.out.print(d + "  "); weekDay = (weekDay + 1) % 7; // 每打印一天后,反应第二天是星期几 if (weekDay == 0) // 如果第二天是星期天,便换行。 System.out.println(); } System.out.println('\n'); } }

java程序的主入口处 public static void main(String[] args) throws IOException { System.out.print("请输入一个年份:"); InputStreamReader ir; // 以下接受从控制台输入 BufferedReader in; ir = new InputStreamReader(System.in); in = new BufferedReader(ir); String s = in.readLine(); year = Integer.parseInt(s); weekDay = firstDay(year); // 计算该年第一天是星期几 System.out.println("\n          " + year + "年          "); printMonth(); } }

运行结果

点击展开全文

更多推荐