1.2.19 string parsing. Compile a constructor that parses string data for the date and transaction types implemented in exercise 1.2.13. It accepts an initial value specified by the string parameter, as shown in table 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]);
}
A:
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 & amp; 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 (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 ());
}
}
Algs4-1.2.19 String Parsing