I have no idea how to write in \" public String dayOfWeek()\" please help thanks
ID: 3539775 • Letter: I
Question
I have no idea how to write in " public String dayOfWeek()" please help thanks!!
public class Date
{
private int year;
private int month;
private int day;
// Construct a Date given the year, month, and day of month.
public Date(int year, int month, int day)
{
// TBD
this.year = year;
this.month = month;
this.day = day;
}
// Return the day of week corresponding to this date.
public String dayOfWeek()
{
// TBD
}
// Is this date same as b?
public boolean equals(Date b)
{
// TBD
if((this.year == b.year) && (this.month == b.month) && (this.day == b.day)) {
return true;
}
return false;
}
// Return a String representation of this date.
public String toString()
{
// TBD
return year + "-" + month + "-" + day;
}
// Test driver.
public static void main(String[] args)
{
Date a = new Date(1974, 7, 8);
Date b = new Date(1879, 3, 14);
Date c = new Date(1879, 3, 14);
System.out.println("Should print 1974-7-8: " + a);
System.out.println("Should print Monday: " + a.dayOfWeek());
System.out.println("Should print 1879-3-14: " + b);
System.out.println("Should print Friday: " + b.dayOfWeek());
System.out.println("Should print false: " + a.equals(b));
System.out.println("Should print true: " + b.equals(c));
}
}
Explanation / Answer
public dayOfWeek(){
if (month<3){
month += 12;
year -= 1 ;
}
int k = year%100;
int j = year/100;
int day = ((date + (((month + 1) * 26) / 10) + k + (k / 4) + (j / 4))+ (5 * j)) % 7;
switch (day){
case 0 : return "Saturday";
case 1 : return "Sunday";
case 2 : return "Monday";
case 3 : return "Tuesday";
case 4 : return "Wednesday";
case 5 : return "Thursday";
case 6 : return "Friday";
default : return "Sunday";
}
}