Algs4-1.2.12为SmartDate添加一个方法dayOfTheWeek()
1.2.12为SmartDate添加一个方法dayOfTheWeek(),为日期中每周的日返回Monday、Tuesday、Wednesday,Thursday,Friday,Saturday或Sunday中的适当值。你可以假定时间是21世纪。
答:
Code:
public class SmartDate
{
private final int myYear;
private final int myMonth;
private final int myDay;
public SmartDate(int month,int day,int year)
{
if(year<0) throw new IllegalArgumentException("year is error.");
if(month<1 || month>12) throw new IllegalArgumentException("month is error.");
if(day<1 || day>31) throw new IllegalArgumentException("day is error.");
if(month%2==0 && day>30) throw new IllegalArgumentException("day is error.");
if(year%400!=0 && (!(year%4==0 && year%100!=0))
&& month==2 && day>28) throw new
IllegalArgumentException("day is error.");
if((year%400==0
|| (year%4==0 && year%100!=0)) && month==2 &&
day>29) throw new IllegalArgumentException("day is error.");
//
myYear=year;
myMonth=month;
myDay=day;
//
}
public int month()
{
return myMonth;
}
public int day()
{
return myDay;
}
public int year()
{
return myYear;
}
public String dayOfTheWeek()
{
int w=(myYear%100+(myYear%100)/4+(myYear-myYear%100)/4-2*(myYear-myYear%100)+26*(myMonth+1)/10+myDay-1)%7;
if(w<0) w=w+7;
String weekstr="";
switch(w)
{
case 0: weekstr="Sunday"; break;
case 1: weekstr="Monday"; break;
case 2: weekstr="Tuesday"; break;
case 3: weekstr="Wednesday"; break;
case 4: weekstr="Thursday"; break;
case 5: weekstr="Friday"; break;
case 6: weekstr="Saturday"; break;
}
return weekstr;
}
public String toString()
{
return month()+"/"+day()+"/"+year();
}
public static void main(String[] args)
{
SmartDate d=new SmartDate(9,18,2016);
StdOut.printf("Date is:%s,WeekDay is:%s",d.toString(),d.dayOfTheWeek());
}
}
参考资料:百度百科:蔡勒公式、维基百科英文版:Zeller's congruence、《离散数学及其应用》原书第七版中文版:除法算法。
注意事项:计算机语言中的模运算可以返回负数,而数学定义中的模运算不能返回负数,这里采用数学定义中的模运算。