Introduction

  • In this blog, I am going to explain about the monthly calendar program in Java

Software Requirements

  • Java, Notepad.
Program
  1. import java.util.*;
  2. import java.text.*;
  3. public class MonthCalender {
  4. public final static String[] monthcalender = {
  5. "January",
  6. "February",
  7. "March",
  8. "April",
  9. "May",
  10. "June",
  11. "July",
  12. "August",
  13. "September",
  14. "October",
  15. "November",
  16. "December"
  17. };
  18. public final static int daysinmonths[] = {
  19. 31,
  20. 28,
  21. 31,
  22. 30,
  23. 31,
  24. 30,
  25. 31,
  26. 31,
  27. 30,
  28. 31,
  29. 30,
  30. 31
  31. };
  32. private void displayMonth(int month, int year) {
  33. // The number of days to leave blank at
  34. // the start of this month.
  35. int blankdays = 0;
  36. System.out.println(" " + monthcalender[month] + " " + year);
  37. if (month < 0 || month > 11) {
  38. throw new IllegalArgumentException(
  39. "Month " + month + " is not valid and must lie in between 0 and 11");
  40. }
  41. GregorianCalendar cldr = new GregorianCalendar(year, month, 1);
  42. System.out.println("Sunday Monday Tuesday Wednesday Thursday Friday Saturday");
  43. // Compute how much to leave before before the first day of the month.
  44. // getDay() returns 0 for Sunday.
  45. blankdays = cldr.get(Calendar.DAY_OF_WEEK) - 1;
  46. int daysInMonth = daysinmonths[month];
  47. if (cldr.isLeapYear(cldr.get(Calendar.YEAR)) && month == 1) {
  48. ++daysInMonth;
  49. }
  50. // Blank out the labels before 1st day of the month
  51. for (int i = 0; i < blankdays; i++) {
  52. System.out.print(" ");
  53. }
  54. for (int i = 1; i <= daysInMonth; i++) {
  55. // This "if" statement is simpler than messing with NumberFormat
  56. if (i <= 9) {
  57. System.out.print(" ");
  58. }
  59. System.out.print(i);
  60. if ((blankdays + i) % 7 == 0) { // Wrap if EOL
  61. System.out.println();
  62. } else {
  63. System.out.print(" ");
  64. }
  65. }
  66. }
  67. /**
  68. * Sole entry point to the class and application.
  69. * @param args Array of String arguments.
  70. */
  71. public static void main(String[] args) {
  72. int mon, yr;
  73. MonthCalender moncldr = new MonthCalender();
  74. if (args.length == 2) {
  75. moncldr.displayMonth(Integer.parseInt(args[0]) - 1, Integer.parseInt(args[1]));
  76. } else {
  77. Calendar todaycldr = Calendar.getInstance();
  78. moncldr.displayMonth(todaycldr.get(Calendar.MONTH), todaycldr.get(Calendar.YEAR));
  79. }
  80. }
  81. }
Output
one