`

利用Calendar输出指定年份的全年日历

 
阅读更多
  1. /**
  2. *@authorbzwm
  3. *
  4. */
  5. importjava.io.BufferedReader;
  6. importjava.io.IOException;
  7. importjava.io.InputStreamReader;
  8. importjava.util.Calendar;
  9. importjava.util.GregorianCalendar;
  10. publicclassCalendarTest{
  11. publicstaticvoidmain(String[]args)throwsIOException{
  12. BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
  13. System.out.print("请输入一个年份:");
  14. Stringyears=in.readLine();
  15. CalendarPrintercp=newCalendarPrinter(years);
  16. cp.printCal();
  17. }
  18. }
  19. classCalendarPrinter{
  20. privateintyear;
  21. privatestaticfinalintmonthCount=12;
  22. publicCalendarPrinter(Stringyears){
  23. if(!years.matches("//d{4}")){
  24. System.out.println("yearthatinputtedisillagel.");
  25. return;
  26. }
  27. year=Integer.parseInt(years);
  28. }
  29. publicvoidprintCal(){
  30. //constructdascurrentdate
  31. GregorianCalendargCal=newGregorianCalendar();
  32. //setyear
  33. gCal.set(Calendar.YEAR,year);
  34. for(intmonth=0;month<monthCount;month++){
  35. gCal.set(Calendar.MONTH,month);
  36. printOut(gCal);
  37. }
  38. }
  39. privatevoidprintOut(Calendarcal){
  40. intmonth=cal.get(Calendar.MONTH);
  41. //setcaltostartdateofthemonth
  42. cal.set(Calendar.DAY_OF_MONTH,1);
  43. intweekday=cal.get(Calendar.DAY_OF_WEEK);
  44. //printheading
  45. System.out.println("SunMonTueWedThuFriSat");
  46. //indentfirstlineofcalendar
  47. for(inti=Calendar.SUNDAY;i<weekday;i++)
  48. System.out.print("");
  49. do{
  50. //printday
  51. intday=cal.get(Calendar.DAY_OF_MONTH);
  52. if(day>0)
  53. System.out.print(""+day+"");
  54. else
  55. System.out.print(""+day+"");
  56. //startanewlineaftereverySaturday
  57. if(weekday==Calendar.SATURDAY)
  58. System.out.println();
  59. //advancedtothenextday
  60. cal.add(Calendar.DAY_OF_MONTH,1);
  61. weekday=cal.get(Calendar.DAY_OF_WEEK);
  62. }while(cal.get(Calendar.MONTH)==month);
  63. //theloopexitswhendisday1ofthenextmonth
  64. //printfinalendoflineifnecessary
  65. if(weekday!=Calendar.SUNDAY)
  66. System.out.println();
  67. }
  68. }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics