Algs4-1.2.19字符串解析

1.2.19字符串解析。为你在练习1.2.13中实现的Date和Transaction类型编写能够解析字符串数据的构造函数。它接受一个String参数指定的初始值,格式如表1.2.20所示:
Partial solution:
public Date(String date)
{
String[] fields = date.split("/");
month = Integer.parseInt(fields[0]);
day = Integer.parseInt(fields[1]);
year = Integer.parseInt(fields[2]);
}
答:
图片

public class SmartDate
{
   private final int myYear;
   private final int myMonth;
   private final int myDay;
  
   public SmartDate(String date)
   {
       String[] words=date.split("/");
       int month=Integer.parseInt(words[0]);
       int day=Integer.parseInt(words[1]);
       int year=Integer.parseInt(words[2]);
       //
      mySmartDate(month,day,year);
      //
       myYear=year;
       myMonth=month;
       myDay=day;
   }
  
    public SmartDate(int month,int day,int year)
    {
        mySmartDate(month,day,year);
        //
        myYear=year;
        myMonth=month;
        myDay=day;
        //
      }
   
    private void mySmartDate(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.");
    }
   
    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\n",d.toString(),d.dayOfTheWeek());
        //
        SmartDate d2=new SmartDate("9/25/2016");
        StdOut.printf("Date is:%s,WeekDay is:%s\n",d2.toString(),d2.dayOfTheWeek());
    }
}
posted @ 2018-10-25 11:51  修电脑的龙生  阅读(159)  评论(0编辑  收藏  举报