Advertisement
lrm2000

Time Converter 2017

Sep 19th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. /*
  2. * AP CS MOOC
  3. * Term 2 - Assignment 1: Time
  4. * A class which represents the time of day in hours and seconds.
  5. */
  6.  
  7. public class Time
  8. {
  9. private int hour;
  10. private int minute;
  11.  
  12. public Time()
  13. {
  14. hour = 00;
  15. minute = 00;
  16. }
  17.  
  18. public Time(int h, int m)
  19. {
  20. hour = h;
  21. minute = m;
  22.  
  23. if (h <= 23 && h >= 1)
  24. {
  25. hour = h;
  26. }
  27. else
  28. hour = 0;
  29.  
  30. if (m <= 59 && m >= 0)
  31. {
  32. minute = m;
  33. }
  34. else
  35. minute = 0;
  36. }
  37.  
  38. /* Returns the time as a String of length 4 in the format: 0819.
  39. * Notice that if the hour or minute is one digit, it should
  40. * print a zero first. For example, 6 should print as 06.
  41. */
  42. public String toString()
  43. {
  44. String min = "";
  45. String ho = "";
  46. if (minute >=0 && minute <= 9)
  47. {
  48. min = "0" + minute;
  49. }
  50. else
  51. min = "" + minute;
  52.  
  53. if (hour >=0 && hour <= 9)
  54. {
  55. ho = "0" + hour;
  56. }
  57. else
  58. ho = "" + hour;
  59.  
  60. String newTime = ho + min;
  61.  
  62. return newTime;
  63. }
  64.  
  65. /*
  66. * Returns the time as a String converted from military time
  67. * to standard time. For example, 0545 becomes 5:45 AM and
  68. * 1306 becomes 1:06 PM.
  69. */
  70. public String convert()
  71. {
  72. String tod = "";
  73. String min = minute + "";
  74. String ho = hour + "";
  75. String standard = "";
  76.  
  77. if (hour > 12 && hour <=23)
  78. {
  79. tod = " PM";
  80. }
  81. else
  82. tod = " AM";
  83. if ( tod == " PM")
  84. {
  85. ho = hour - 12 + "";
  86. }
  87. if (hour == 12)
  88. {
  89. tod = " PM";
  90. }
  91. if (hour == 0)
  92. {
  93. ho = "12";
  94. }
  95. if (minute < 10)
  96. min = "0" + minute;
  97.  
  98. standard = ho + ":" + min + tod;
  99. return standard;
  100. }
  101.  
  102. /*
  103. * Advances the time by one minute.
  104. * Remember that 60 minutes = 1 hour.
  105. * Therefore, if your time was 0359, and you add one minute,
  106. * it becomes 0400. 2359 should increment to 0000.
  107. */
  108. public void increment()
  109. {
  110. minute ++;
  111. if (minute == 60)
  112. {
  113. hour ++;
  114. minute = 0;
  115. }
  116. if (hour == 24)
  117. {
  118. hour = 0;
  119. minute = 0;
  120. }
  121.  
  122.  
  123.  
  124. }
  125.  
  126. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement