1packagecodeTask_FangFa;2//5.34 使用zeller公式,打印某年某月的日历信息。3importjava.util.Scanner;4publicclassPRintRiLi {5publicstaticvoidmain(String[] args){6Scanner input =newScanner(System.in);7System.out.println("请输入需要打印日历的年份:");8intyear =input.nextInt();9System.out.println("请输入需要打印日历的月份:");10intmonth =input.nextInt();11printTitle(year,month);12printBody(year,month);1314}1516publicstaticvoidprintTitle(intyear,intmonth){//第二战场--头17System.out.println(" 日 历");18System.out.println(" "+getMonth(month)+" "+year);19System.out.println(" 星期日 星期一 星期二 星期三 星期四 星期五 星期六");20System.out.println("--------------------------------------------------");21}2223publicstaticString getMonth(intmonth){//这就不说啥了2425switch(month){26case1:return"一月";27case2:return"二月";28case3:return"三月";29case4:return"四月";30case5:return"五月";31case6:return"六月";32case7:return"七月";33case8:return"八月";34case9:return"九月";35case10:return"十月";36case11:return"十一月";37case12:return"十二月";38}39System.out.println("输入的月份出错,程序退出!");40System.exit(0);41return"-1";42}4344publicstaticvoidprintBody(intyear,intmonth){//主战场--可要看仔细了。45intcount =getXingQi(year,month);46intnim = getNumberInMonth(year,month);//nim 全拼是 number in month.47intday = 1;//每月的日子,从 1 开始。48switch(count){49case0 : count = 1;
break;50case1 : count = 2;
break;51case2 : count = 3;
break;52case3 : count = 4;
break;53case4 : count = 5;
break;54case5 : count = 6;
break;55case6 : count = 7;
break;56}57for(inti =1;i<count;i++){58System.out.printf("%7s"," ");59}60while(day<nim){6162while(count%7!=0){63System.out.printf("%7d",day);64if(day==nim)65System.exit(0);66count++;67day++;6869}70System.out.printf("%7d\n",day);71count++;72day++;7374}7576}777879publicstaticintgetXingQi(intyear,intmonth){//得到某月1号是星期几。 这里会用到zeller公式。80intm =month;81if(month == 1){82m = 13;83year--;84}85elseif(month ==2){86m = 14;87year--;88}89intd = 1;90intc = year/100;91inty = year%100;92intw1 = y+y/4+c/4-2*c+26*(m+1)/10+d-1;93intw = (w1%7+7)%7;94returnw ;95}9697publicstaticintgetNumberInMonth(intyear,intmonth){//返回某月共有几天。98if(isRunNian(year)){99switch(month){100case1 :return31;101case2 :return29;102case3 :return31;103case4 :return30;104case5 :return31;105case6 :return30;106case7 :return31;107case8 :return31;108case9 :return30;109case10 :return31;110case11:return30;111case12 :return31;112}113}114else{115switch(month){116case1 :return31;117case2 :return28;118case3 :return31;119case4 :return30;120case5 :return31;121case6 :return30;122case7 :return31;123case8 :return31;124case9 :return30;125case10 :return31;126case11:return30;127case12 :return31;128}129}130return-1;//错误情况下的返回值。131}132133publicstaticbooleanisRunNian(intyear){//判断闰年。是就true134if(year%400==0||(year%4==0&year%100!=0))135returntrue;136returnfalse;137}138}