年历"/>
Java控制台输出任意一年年历
之前用C语言写过输出任意一年年历的程序,现在转为Java语言,并在控制台输出,完整代码如下
public class PrintAnyYear {public static void main(String[] args) {int year = 2019;System.out.print("请输入一个年份:");Scanner scanner = new Scanner(System.in);year = scanner.nextInt();System.out.println(String.format(Locale.CHINA, "\n\t\t\t\t\t\t\t\t%d年\n", year));printYearData(getYearData(year));scanner.close();}/*判断闰年*/private static boolean judgeLeap(int year) {if (year < 1800) {return year % 4 == 0;} else {return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);}}/*获取1~year这些年中的闰年数*/private static int getCountofLeap(int year) {int count = 0;for (int i = 1; i < year; i++) {if (judgeLeap(i))count++;}return count;}/*获取该年每月第一天位置*/private static int[] getFirstDay(int year) {int[] firstDay = new int[13];int FirstDay1 = 6;//初始化公元1年第一天位置int[] lastDay = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};//平年每月天数int LeapCount = getCountofLeap(year);//1~year之间的闰年数long temp = 365 * (year - 1);if (year > 1752) {temp = temp - 11;}firstDay[1] = (int) ((temp + LeapCount + FirstDay1) % 7);//该年第一个月第一天的位置if (judgeLeap(year)) {//闰年二月特殊考虑lastDay[2] = 29;}if (year == 1752) {//1752年特殊考虑lastDay[9] = 19;}for (int i = 2; i < 13; i++) {//获取其他月份的第一天位置firstDay[i] = (lastDay[i - 1] + firstDay[i - 1]) % 7;}return firstDay;}/*填充一年数据*/private static int[][][] getYearData(int year) {int[][][] oneYear = new int[12][6][7];int[] lastDay = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};int[] firstDay = getFirstDay(year);if (judgeLeap(year)) {lastDay[2] = 29;}int first, last;for (int month = 0; month < 12; month++) {first = 1;last = 1;for (int week = 0; week < 6; week++) {for (int day = 0; day < 7; day++) {//填充一周if (first > firstDay[month + 1] && last <= lastDay[month + 1]) {oneYear[month][week][day] = last;if (year == 1752 && month == 8 && last == 2) {//1752年9月特殊考虑last = last + 11;}last++;} else {oneYear[month][week][day] = 0;}first++;}}}return oneYear;}/*输出一年数据*/private static void printYearData(int[][][] yearData) {String[] moth = {"一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"};for (int i = 0, j = 0; i < 4; i++) {System.out.println(String.format("\t\t %s\t\t\t\t\t %s\t\t\t\t\t %s", moth[j], moth[j + 1], moth[j + 2]));System.out.println(" 日 一 二 三 四 五 六\t 日 一 二 三 四 五 六\t 日 一 二 三 四 五 六");for (int week = 0; week < 6; week++) {for (int month = j; month < j + 3; month++) {for (int day = 0; day < 7; day++)//输出一周{if (yearData[month][week][day] == 0) {System.out.print(String.format("%3c", ' '));} else {System.out.print(String.format(Locale.CHINA, "%3d", yearData[month][week][day]));}}System.out.print("\t");}System.out.println();}j = j + 3;}}}
运行效果:
更多推荐
Java控制台输出任意一年年历
发布评论