You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

6 years ago
6 years ago
  1. // The IncDate class
  2. // Do not make changes to anything other than the body of increment() method
  3. // Your name here
  4. public class IncDate extends Date
  5. {
  6. // copy constructor
  7. public IncDate(Date o)
  8. {
  9. super(o.m_month, o.m_day, o.m_year);
  10. }
  11. // constructor
  12. public IncDate(int month, int day, int year)
  13. {
  14. super(month, day, year);
  15. }
  16. public void addDays(int numDays)
  17. {
  18. // TODO: implement this method
  19. int days_to_add = numDays;
  20. int[] MONTHS = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  21. boolean is_leap = (m_year % 400 == 0) || ((m_year % 4 == 0) && !(m_year % 100 == 0));
  22. for (int current_month = 0; current_month < m_month-1; current_month ++)
  23. days_to_add += MONTHS[current_month];
  24. if ((m_month > 2) && is_leap)
  25. days_to_add += 1;
  26. days_to_add += m_day-1;
  27. m_month = 1;
  28. m_day = 1;
  29. while (days_to_add > 365) {
  30. is_leap = (m_year % 400 == 0) || ((m_year % 4 == 0) && !(m_year % 100 == 0));
  31. if (is_leap)
  32. days_to_add -= 1;
  33. days_to_add -= 365;
  34. m_year += 1;
  35. }
  36. is_leap = (m_year % 400 == 0) || ((m_year % 4 == 0) && !(m_year % 100 == 0));
  37. if (is_leap)
  38. MONTHS[1] +=1;
  39. while (days_to_add >= MONTHS[m_month-1]) {
  40. days_to_add -= MONTHS[m_month-1];
  41. m_month += 1;
  42. }
  43. m_day=days_to_add+1;
  44. }
  45. }