1 ImportJava.util.Calendar;2 ImportJava.util.Scanner;3 Public classPROBLEM5 {4 Public Static voidPrint_ (intYearintFirstday,string[] month,intKint[] days) {5 if(firstday>=7) firstday-=7;//Boundary Processing6System.out.printf ("\t\t%s%5d\n", month[k],year);//Print Month7 for(inti=1;i<=47;i++) System.out.print ("-");//Print Split Line8System.out.printf ("\n%4s%7s%7s%7s%7s%7s%7s\n", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");9 intKey=1;Ten intLine=1; One intN=firstday+1; A intMod= (8-firstday)%7; - while(line==1&firstday>0&n>1) {//Print the space before the first day -System.out.printf ("%7s", "" "); then--; - } -A: while(true) { - for(intj=1;j<=7;j++,key++) {//seven days a week pointer key is the number of days in the month pointer + if(key%7==mod|key==1) {//determine the number of spaces -System.out.printf ("%3d", key); +}ElseSystem.out.printf ("%7d", key); A if(Line==1&key==7-firstday) {//print 7-n days on the first line atkey++; - Break; - } - if(Key==days[k]) BreakA; - } -line++; in System.out.println (); - } to System.out.println (); + if(k!=11) Print_ (year,days[k]%7+firstday,month,++k,days);//continue calling method if K is not equal to 12 - } the Public Static voidMain (string[] args) { *Scanner input=NewScanner (system.in); $System.out.print ("Enter Year:");Panax Notoginseng intYear=input.nextint (); -Calendar acalendar=calendar.getinstance (); theAcalendar.set (year, 0, 1);//year,1,1 + intFirstday=acalendar.get (Calendar.day_of_week)-1;//gets the number of weeks of the first day of the input year ASystem.out.println ();//the stored month is easy to call in the array theString[] Month= {"January", "February", "March", "April", "may", "June", "July", "August", "Sptember", "October", " November "," December "}; + int[] days= {31,28,31,30,31,30,31,31,30,31,30,31};//Pre-save days per month - if((year%4==0&year%100!=0) |year%400==0) days[1]=29;//Leap Year judgment $Print_ (year,firstday,month,0,days);//parameter 1: Year parameter 2: First day of the week parameter 3: Month string parameter 4: currently printed month-1 parameter 5: Number of days per month $ input.close (); - } -}
Output effect:
Enter year in Java print calendar