【程序说明】该程序实现了输出任意一年的日历,并输出该年中任意一天是该年的第几周。
【规定】①闰年366天,2月29天;平年365天,2月28天。
②周日为某月的第一天,周六为该月的最后一天。
③某年的1月1号为该年的第一天,属于该年的第一周。
程序运行结果部分截图如下:
【注意】2018.01.31和2018.02.01同属于2018年的第5周!
代码如下-Java:
public class WanNianLi {//某年是否是润年public static boolean isLeapYear(int year){boolean isOK;isOK = year%4==0 && year%100!=0 || year%400==0 ? true:false;return isOK;}//某年有多少天public static int yearDays(int year){int days;//润年366天二月29天,平年365天二月28天return days = isLeapYear(year) ? 366 : 365;}//某年某月有多少天public static int yearMonthDays(int year,int month){int days = 0;switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:days=31;break;case 4:case 6:case 9:case 11:days=30;break;case 2:days = isLeapYear(year)?29:28;break;}return days;}//某年某月第一天距离2000.01.01有多少天public static int yearMonthDayTo20000101(int year,int month){int days = 0;if(year>=2000){//年for (int i = 2000; i < year; i++) {days += yearDays(i);}//月for (int j = 1; j < month; j++) {days += yearMonthDays(year,j);}}else{//eg:1998.06.01for (int i = year+1; i<2000; i++) {days += yearDays(i);}for(int j = month ; j<=12; j++){days += yearMonthDays(year, j);}}return days;}//某年某月1号是星期几public static int weekDay(int year, int month){int dayNum = 99;//周日记为0,周六记为6,99代表错误int n = yearMonthDayTo20000101(year,month);if(year>=2000){dayNum = (6+n)%7;}else{dayNum = 6-n%7;}return dayNum;}//静态变量weekNum表示一天中的某一天属于该年的第几周static int weekNum = 0;//周数//显示某年某月的日历public static void displayYearMonth(int year, int m) {System.out.println("\t\t ————"+year+"———"+m+"————");System.out.println("日\t一\t二\t三\t四\t五\t六\t周");int count = 0;//定义一个计数器,记录当前将要输出的天在日历表中的位置。例如2018.1.1的count=1count = weekDay(year, m);//日历的第一行空多少格,count[0,6]for(int j = 0; j < count; j++)//空count-1格,第count的位置打印1号System.out.print("\t");for(int i = 1; i <= yearMonthDays(year, m); i++){if( (count+1)%8 == 0 ){//该输出周数weekNum的时候System.out.println(++weekNum);count++;}System.out.print(i+"\t");//输出号数count++;//例如2018.01,i=31输出后的count=36,if(i==yearMonthDays(year, m)){//输出某月最后一天时if( (count+1)%8 != 0){//如果该月的最后一天不是周六do {System.out.print("\t");count++;} while ( (count+1)%8 != 0);//当满足条件是继续循环,直到不满足条件时结束循环}System.out.println(++weekNum); weekNum--;//因为该月的最有一天不是周六,所以下月的第一天与该月的最后一天时同一周}}}//显示某年的日历public static void displayYear(int year){for(int m = 1; m <=12; m++){displayYearMonth(year,m);System.out.println();}}public static void main(String[] args) {displayYear(2018);//输出2018年的日历
// displayYearMonth(2018,1);//输出2018年1月的日历
// weekDay(2018,6);//输出2018年6月有几天
// yearMonthDayTo20000101(2018,1);//输出2018年1月1日距离2000.01.01有几天}}