Wednesday, October 6, 2010

Fun with Java-Part 1

Let's have some fun using Java

Let's build a calendar using Java
The logic behind developing a calendar is very simple. You just have to know a particular date and which date it was, and on this basis you can calculate any date.
For example 1st January 1900 was a Monday, knowing this you can calculate any day.
How???
First of all you have to calculate the no. of days in between your desired date and 1st january 1900. Then divide the no. of days by 7.
If the remainder is 0 (zero) that day is also a Monday, if the diff. is 1 the day is Tuesday and so on.
If(No. of Days) % 7 == 0 (Then Monday)
If(No. of Days) % 7 == 1 (Then Tuesday )
…………………………….
If(No. of Days) % 7 == 6 (Then Sunday )
How to find out the no. of days ???
Very simple!! First find out the no. of years,then the no. of leap years in between your req. yr. and 1900.
Total No. of Days = (No. of yrs. * 365)+(No. of leap years)+(No. of days in the given yr. before the req. date)
For example, let us consider that you want to find out which day will be 1st Nov. 2008.
No. of yrs. Between 1900 & 2008 = 108
No. of leap yrs.= 26
No. of days in the yr. 2008 before 1st nov. = 304
So Total No. of Days= (108*365) + 26 + 304= 39750
But do not forget that the yr. 2008 is itself a leap yr. so add another day to the total count (+1) = 39751

39751 % 7 = 5 (i.e. Saturday)  

Now, try to implement this in code. You will get the source code in
the next week.
Some Hints:
(i) How to find whether a year is a leap yr. or not??
 (If the yr. is divisible by 400, it is undoubtedly a leap yr. ex. 2000,1600, etc. If the yr. is divisible by 4 but not divisible by 100 it is a leap yr. ex. 1900 is divisible by 4 but since it is also divisible by 100 it is not a leap yr. whereas 2008 is divisible by 4 & not divisible by100 so it is a leap yr.
(ii) Use  long as the data type to store the no. of days as the number may be huge.
(iii) Follow OOP concept. Like keep the main calendar logic in a separate Java class, and create a driver class(main class) to feed year and month to the Calendar class.

N.B: I will be posting the code in the following week, try to solve it in the meanwhile, post it if you succeed.

Output Should be as following



No comments:

Post a Comment