I have an assignment to create a method to retrieve the proper day of the week for any given date, without using the Java calendar. After countless hours of trying to implement the algorithm in the outline, I've finally finished it and it appears to work! I feel like it's really sloppy. Any tips on how to clean it up or remove any dead code you see?
Here's the algorithm I had to implement:
- Only look at the last two digits of the year and determine how many 12s fit in it
- Look at the remainder of this division
- How many 4s fit into that remainder
- Add the day of the month
Add the month code:
Jan = 1
Feb = 4
Mar = 4
Apr = 0
May = 2
Jun = 5
Jul = 0
Aug = 3
Sep = 6
Oct = 1
Nov = 4
Dec = 6Add your numbers, then mod by 7
Some dates require special offsets:
- January and February dates in leap years: subtract 1 from step 5
- Dates in the 1600s: add 6 to step 5
- Dates in the 1700s: add 4 to step 5
- Dates in the 1800s: add 2 to step 5
- Dates in the 2000s: add 6 to step 5
- Dates in the 2100s: add 4 to step 5
public String getDayOfTheWeek() { int shortYear = yearNumber % ONE_HUND_MOD; /* gives the last two digits of the four digit year */ int anotherShortYear = yearNumber % ONE_HUND_MOD; /* gives the last two digits of the four digit year to another variable */ int twelvesFirstStep = (shortYear / TWELVE_DIVIDE); /* gives the number of 12s that fit in the last two digits of the year(step1) */ int secondStepRemainder = anotherShortYear % TWELVE; /* gives the remainder of whats left from dividing the last two digits of year by 12(step 2) */ int thirdStepRemainder = secondStepRemainder / FOUR; /* gives the division by 4 of the remainder of the previous step (step 3) */ int numericalDay = 0; int temp = twelvesFirstStep + secondStepRemainder + thirdStepRemainder + dayNumber +getMonthCode(); // all variables combined if (monthNumber ==JANUARY || monthNumber == FEBRUARY && isLeapYear() == true) { temp--; } else { temp = temp; } if (yearNumber >= CENTURY_SIXTEEN && yearNumber < CENTURY_SEVENTEEN || yearNumber >= CENTURY_TWENTY && yearNumber < CENTURY_TWENTY_ONE) { numericalDay = (SIX+temp) % MOD_BY_SEVEN; } else if(yearNumber >=CENTURY_SEVENTEEN && yearNumber < CENTURY_EIGHTEEN || yearNumber >= CENTURY_TWENTY_ONE && yearNumber <CENTURY_TWENTY_TWO) { numericalDay = (FOUR+temp) % MOD_BY_SEVEN; } else if(yearNumber >=CENTURY_EIGHTEEN && yearNumber < CENTURY_NINETEEN) { numericalDay =(TWO+temp) % MOD_BY_SEVEN; } else { numericalDay = temp % MOD_BY_SEVEN; } if(numericalDay == TRANSLATED_DAY_SAT) { return SATURDAY_STRING; } else if(numericalDay == TRANSLATED_DAY_SUN) { return SUNDAY_STRING; } else if(numericalDay ==TRANSLATED_DAY_MON) { return MONDAY_STRING; } else if(numericalDay == TRANSLATED_DAY_TUES) { return TUESDAY_STRING; } else if(numericalDay == TRANSLATED_DAY_WED) { return WEDNSEDAY_STRING; } else if(numericalDay ==TRANSLATED_DAY_THU) { return THURSDAY_STRING; } else { return FRIDAY_STRING; } }