Advertisement
Guest User

Untitled

a guest
Feb 27th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. /*
  2. * AP CS MOOC
  3. * Term 2 - Assignment 4: Time Comparable
  4. * You can use this solution to Assignment 1 in order to create a comparable time object.
  5. * You will need to change the class so that it implements the comparable interface.
  6. */
  7.  
  8. public class Time implements Comparable
  9. {
  10. private int hour;
  11. private int minute;
  12.  
  13. /*
  14. * Sets the default time to 12:00.
  15. */
  16. public Time ()
  17. {
  18. this(12, 0);
  19. }
  20.  
  21. /*
  22. * Sets hour to h and minute to m.
  23. */
  24. public Time (int h, int m)
  25. {
  26. hour = 0;
  27. minute = 0;
  28. if (h >=1 && h <= 23)
  29. hour = h;
  30. if (m >= 1 && m <= 59)
  31. minute = m;
  32.  
  33. }
  34. public int compareTo(Object other)
  35. {
  36. Time temp = (Time) other;
  37. int num = 0;
  38. if (temp.hour<hour)
  39. {
  40. num = 1;
  41. }
  42. else if (temp.hour==hour)
  43. {
  44. if (temp.minute<minute)
  45. {
  46. num = 1;
  47. }
  48. else if (temp.minute==minute)
  49. {
  50. num = 0;
  51. }
  52. else
  53. {
  54. num = -1;
  55. }
  56. }
  57. else
  58. {
  59. num = -1;
  60. }
  61. return num;
  62. }
  63. public String difference(Time t)
  64. {
  65. Time temp = (Time) t;
  66. String h = "";
  67. String m = "";
  68. if (t.hour>hour)
  69. {
  70. /*if ((t.hour-hour)>12)
  71. {
  72. h+=(t.hour-hour)-12;
  73. }
  74. else */
  75. {
  76. h+=t.hour-hour;
  77. }
  78. }
  79. else if (t.hour<hour)
  80. {
  81. /*if ((hour-t.hour)>12)
  82. {
  83. h+=(hour-t.hour)-12;
  84. }
  85. else */
  86. {
  87. h+=hour-t.hour;
  88. }
  89. }
  90. else
  91. {
  92. h+=0;
  93. h+=0;
  94. }
  95. if (t.minute>minute)
  96. {
  97. m+=(t.minute-minute);
  98. }
  99. else if (minute>t.minute)
  100. {
  101. m+=(minute-t.minute);
  102. }
  103. else
  104. {
  105. m+=0;
  106. m+=0;
  107. }
  108. return h + ":" + m;
  109. }
  110.  
  111. /*
  112. * Returns the time as a String of length 4 in the format: 0819.
  113. */
  114. public String toString ()
  115. {
  116.  
  117. String h = "";
  118. String m = "";
  119. if ( hour <10)
  120. h +="0";
  121. if (minute <10)
  122. m +="0";
  123. h += hour;
  124. m+=minute;
  125.  
  126. return "" + h + "" + m;
  127. }
  128. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement