Creating a Real Calendar in Java

Problem:

Write a program that prompt the user to enter the year and the month and later print the calendar for the month of the year. You are free to solve the problem in your own way, or you could follow with the tips; as long as you get same output. To print a body, first pad some space before the start day and then print the lines for every week, as shown in the output.
The program does validate user input. For instance, if the user enters either a month not in the range between 1 and 12 or a year before 1800, the program would display an erroneous calendar. To avoid this error, add an if statement to check the input before printing the calendar.

The isLeapYear(int year) method can be implemented using the following code: return (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0));

Use the following facts to implement getTotalNumberOfDaysInMonth(int year, int month):
1) January, March, May, July, August, October, and December have thirty-one days.
2) April, June, September, and November have thirty days.
3) February has twenty-eight days during a regular year and twenty-nine days during a leap year. A regular year, therefore, has 365 days, whereas a leap year has 366 days.

To implement getTotalNumberOfDays(int year, int month), you need to compute the total number of days (totalNumberOfDays) between January 1, 1800 and the first day of the calendar month. You could find the total number of days between the year 1800 and the calendar year and then figure out the total number of days prior to the calendar month in the calendar year. The sum of these two totals is totalNumberOfDays.

To print a body, first pad some space before the start day and then print the lines for every week, as shown for December 2012. Method abstraction modularizes programs in a neat, hierarchical manner. Programs written as collections of concise methods are easier to write, debug, maintain, and modify than would otherwise be the case. This writing style also promotes method reusability.

When implementing a large program, use the top-down or bottom-up approach. Do not write the entire program at once. This approach seems to take more time for coding (because you are repeatedly compiling and running the program), but it actually saves time and makes debugging easier.

This program prints calendars for a month but could easily be modified to print calendars for a whole year. Although it can only print months after January 1800, it could be modified to trace the day of a month before 1800.


Output:

Enter full year (e.g., 2001): 2012
Enter month in number between 1 and 12: 12
December 2012
–––––––––––––––––––––––––––––
Sun Mon Tue Wed Thu Fri Sat
1
2   3   4   5   6   7   8
9   10  11  12  13  14  15
16  17  18  19  20  21  22
23  24  25  26  27  28  29
30  31


Solution:

 import java.util.Scanner;

    public class PrintCalendar {

      /** Main method */

      public static void main(String[] args) {
      Scanner scan = new Scanner (System.in);

      //Prompt the user to enter year
      System.out.print("Enter full year (e.g., 2001): ");
      int year = scan.nextInt();

      // Prompt the user to enter month
      System.out.print("Enter month in number between 1 and 12: ");
      int month = scan.nextInt();

      // Print calendar for the month of the year
       if (month < 1 || month > 12 || year < 1980)
        System.out.println("Wrong input!");
        else
            printMonth(year, month);

    }
     /** Print the calendar for a month in a year */

      static void printMonth(int year, int month) {

      //Print the headings of the calendar
       printMonthTitle(year, month);

      //Print the body of the calendar
       printMonthBody(year, month);
     }

     /** Print the month title, e.g., May, 1999 */

     static void printMonthTitle(int year, int month) {

     System.out.println("         " + getMonthName(month) + " " + year);
     System.out.println("–––––––––––––––––––––––––––––");
     System.out.println(" Sun Mon Tue Wed Thu Fri Sat");

     }

     /** Get the English name for the month */
     static String getMonthName(int month) {
       String monthName = null;
       switch (month) {
         case 1: monthName = "January"; break;
         case 2: monthName = "February"; break;
         case 3: monthName = "March"; break;
         case 4: monthName = "April"; break;
         case 5: monthName = "May"; break;
         case 6: monthName = "June"; break;
         case 7: monthName = "July"; break;
         case 8: monthName = "August"; break;
         case 9: monthName = "September"; break;
         case 10: monthName = "October"; break;
         case 11: monthName = "November"; break;
         case 12: monthName = "December";
       }
       return monthName;
     }

     /** Print month body */
     static void printMonthBody(int year, int month) {

       // Get start day of the week for the first date in the month
       int startDay = getStartDay(year, month);

       // Get number of days in the month
       int numberOfDaysInMonth = getNumberOfDaysInMonth(year, month);

       // Pad space before the first day of the month
       int i = 0;
       for (i = 0; i < startDay; i++)
         System.out.print("    ");
       for (i = 1; i <= numberOfDaysInMonth; i++) {
         if (i < 10)
           System.out.print("   " + i);
         else
           System.out.print("  " + i);
         if ((i + startDay) % 7 == 0)
           System.out.println();
       }
       System.out.println();
     }

     /** Get the start day of the first day in a month */

    static int getStartDay(int year, int month) {

       //Get total number of days since 1/1/1800
       int startDay1800 = 3;
       int totalNumberOfDays = getTotalNumberOfDays(year, month);

       //Return the start day
       return (totalNumberOfDays + startDay1800) % 7;
     }

     /** Get the total number of days since January 1, 1800 */

     static int getTotalNumberOfDays(int year, int month) {
      int total = 0;

      //Get the total days from 1800 to year - 1
      for (int i = 1800; i < year; i++)
      if (isLeapYear(i))
         total = total + 366;
       else
         total = total + 365;
 
       //Add days from January to the month prior to the calendar month
       for (int i = 1; i < month; i++)
         total = total + getNumberOfDaysInMonth(year, i);
 
       return total;
     }
 
     /** Get the number of days in a month */

     static int getNumberOfDaysInMonth(int year, int month) {
       if (month == 1 || month == 3 || month == 5 || month == 7 ||
         month == 8 || month == 10 || month == 12)
         return 31;
 
       if (month == 4 || month == 6 || month == 9 || month == 11)
         return 30;
 
       if (month == 2) return isLeapYear(year) ? 29 : 28;
 
       return 0; // If month is incorrect
     }
 
     /** Determine if it is a leap year */
     static boolean isLeapYear(int year) {
       return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
     }
 }


23 comments :

  1. A teacher present be assigned to you, and they will be they to free support all through the arrangement stage. java programming

    ReplyDelete



  2. Thanks for posting useful information.You have provided an nice article, Thank you very much for this one. And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things...Really it was an awesome article...very interesting to read..
    please sharing like this information......
    Android training in chennai
    Ios training in chennai

    ReplyDelete
  3. I can set up my new idea from this post. It gives in depth information. Thanks for this valuable information for all,.. July Calendar 2018 Template

    ReplyDelete
  4. Thank you for sharing amazing ideas for real calendar.

    ReplyDelete
  5. Thanks for the Informative Post . The only way to succeed in the life is education . Get your self update about the occupational health and safety information's by joining thevb .net training in chennai | c sharp training in chennai

    ReplyDelete
  6. I believe that your blog will surely help the readers who are really in need of this vital piece of information. Waiting for your updates.
    Selenium Training in Bangalore
    Selenium Training Institutes in Bangalore
    Selenium Course in Bangalore

    ReplyDelete
  7. Thanks for posting the blog and it is very useful when i read.
    Manual Testing Training in Chennai

    ReplyDelete
  8. Get organized for next year with our 2021 annual calendar templates do not want color or do not have a color printer? These free Printable calendar2021are now available in color but are designed to print beautifully in black and white or greyscale too.

    ReplyDelete

  9. If you want to make note card sized calendars, just change your paper size to note card and the maker will shrink everything down to note card size without loss of quality. The printable calendars 2021 the free printable templates are editable, so go ahead and personalize using the office application or you can use our online calendar creator tool.

    ReplyDelete
  10. I mean, why would you even want to spend your time messing around with a DIY logo maker when you can hire someone else to do the work for you for a cheaper price online cheap logo designs

    ReplyDelete
  11. That was very informative and useful blogs. Keep up with your writing.
    Java Classes in Nagpur

    ReplyDelete

  12. Great blog! This comprehensive guide provides clear instructions and insights for creating a real calendar in Java, covering everything from user input validation to the implementation of methods for calculating leap years and total number of days in a month.
    Also Read: Java Spring Boot Simplifying Enterprise Application Development

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact