最近在复习Java基础知识,顺手写了一个万年历,整体都写在了一个类里面,其实写这种无工具类的万年历实现,用 c 或 c++ 语言更好一点,整体流程更清晰,快捷。不管怎样,作为入门的程序,掌握其中逻辑与基本思想才是重中之重,好了,废话不多说,直接上代码,欢迎批评指正。
静态变量与主函数
import java.util.Scanner;
/* 实现某年/某月的日历输出
* 1970年1月1日,星期四,平年,狗年
* 1900年1月1日,星期一,平年,鼠年*/
public class Calendar {
static int[] years = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static int[] yearsPlus = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static char[] an = { '鼠', '牛', '虎', '兔', '龙', '蛇', '马', '羊', '猴', '鸡', '狗', '猪' };
static final int YEARBASE = 1900;// 1900年基准
static final int YEARMAX = 2100;// 2100年最大值
static final int WEEK = 1; // 1月1日为星期1
static final int AN = 1; // 鼠年
public static void main(String[] args) {
int year = YEARBASE;
int month = 0;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
do {
System.out.println("请输入年份:(" + YEARBASE + "-" + YEARMAX + ")");
year = sc.nextInt();
sc.nextLine();
} while (year < YEARBASE || year > 2100);
do {
System.out.println("请输入月份:(如只想显示年历可不输)");
String nl = sc.nextLine() + "";
month = Integer.parseInt(nl.equals("") ? "0" : nl);
} while (month < 0 || month > 12);
if (month == 0) {
print(year);
} else {
print(year, month);
}
}
工具方法
/*获取是否闰年 */
public static boolean judge(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
} else {
return false;
}
}
/* 获取某年生肖 */
public static int ani(int year) {
return ((year - YEARBASE + AN - 1) % 12);
}
/* 获取某月的天数(加是否闰年条件) */
public static int count(boolean judge, int month) {
if (judge) {
return yearsPlus[month - 1];
} else {
return years[month - 1];
}
}
/* 获取某年某月的1日星期几 */
public static int number(int year, int month) {
int num = 0;
for (int i = YEARBASE; i < year; i++) {
if (judge(i)) {
num += 366;
} else {
num += 365;
}
}
for (int i = 1; i < month; i++) {
if (judge(year)) {
num += yearsPlus[i - 1];
} else {
num += years[i - 1];
}
}
return (num + WEEK) % 7;
}
输出方法
/* 输出某月历表头 */
public static void show(int month) {
System.out.println("\n -----------" + month + " 月" + "-----------");
System.out.println(" 日 一 二 三 四 五 六");
}
/* 输出某年的年历 */
public static void print(int year) {
System.out.print("该年是:" + an[ani(year)] + "年");
if (judge(year)) {
System.out.println("(润)");
} else {
System.out.println("(平)");
}
for (int month = 1; month <= 12; month++) {
print(year, month);
}
}
/* 输出某年某月的月历 */
public static void print(int year, int month) {
show(month);
int week = number(year, month);
for (int k = 1; k <= week % 7; k++) {
System.out.print(" ");
}
for (int date = 1; date <= count(judge(year), month); date++) {
if (((date - 1 + week) % 7 == 0) && (date != 1)) {
System.out.println();
}
if (date < 10) {
System.out.print(" " + date);
} else {
System.out.print(" " + date);
}
}
System.out.println();
}