Reputation: 1591
I'm trying to write a Date class with doomsday rule, in which when the user inputs a year, month and day in a test class, it would output the day of the week.
With the codes below I can find out the dooms day of the year from 1100 to 2900, but then where do I go from here?
(I'm new to Java, so if my code can be cleaner please let me know.
private int year;
private int month;
private int day;
public Set <Integer> tue = new HashSet <Integer> (Arrays.asList(20,16,24,28,12));
public Set <Integer> fri = new HashSet <Integer> (Arrays.asList(18,14,22,26));
public Set <Integer> sun = new HashSet <Integer> (Arrays.asList(21,17,13,25,29));
public Set <Integer> wed = new HashSet <Integer> (Arrays.asList(19,15,23,27,11));
public int getDoomsDay() {
int y = Integer.parseInt(Integer.toString(this.year).substring(0,2));
int c;
if(tue.contains(y)){
c = 2;
}
else if(fri.contains(y)){
c = 5;
}
else if(sun.contains(y)) {
c = 0;
}
else {
c = 3;
}
int d = Integer.parseInt(Integer.toString(this.year).substring(2,4));
int s = d/12;
int t = d%12;
int f = t/s;
int b;
if((c+s+t+f) > 6) {
b = (c+s+t+f)%7;
}
else {
b = (c+s+t+f);
}
if(this.year % 4 == 0 && this.year % 100 != 0) {
return b +1;
}
else {
return b;
}
}
Upvotes: 0
Views: 103
Reputation: 40024
Here is another method to compute the day of the week for an arbitrary date. The formula is based on March
being the first month of the year, so adjustments need to be made when using our dating system as input.
private static String[] weekdays= {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
public static String dayOfWeek(int m, int d, int y) {
int c = y / 100;
y = y % 100;
m = m - 2;
if (m <= 0) {
y = y > 0 ? y-1 : 99;
c--;
m += 12;
}
// basic formula here.
int wd = (d + (int) (.2 * (13 * m - 1)) + y + y / 4 + c / 4
- 2 * c) % 7;
return weekdays[wd];
}
The explanation and derivation is not hard to understand but it is lengthy and thus omitted here. It is from Invitation to Number Theory by Oyestein Ore. Fortunately, a PDF version of the book is online at Invitation to Number Theory. Check out pages 102 - 107.
Upvotes: 2
Reputation: 27946
There are lots of improvements you could make. I'll mention a few here:
Firstly, don't use strings to get the century and year-in-century
int century = year / 100;
int yearInCentury = year % 100;
Secondly, if I understand the algorithm correctly, you don't need to have lists of centuries to convert to anchor day of week. You can calculate the doomsday with:
int anchor = (5 * (century % 4)) % 7 + 2;
Thirdly,
if ((c+s+t+f) > 6) {
b = (c+s+t+f)%7;
} else {
b = (c+s+t+f);
}
Is actually just the same as
b = (c+s+t+f) % 7;
There are plenty of other improvements but hopefully that's enough to answer your question.
Upvotes: 0