Guest User

Clock Assignment

a guest
May 8th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1.  
  2. public class Clock {
  3. // Fields of the class
  4. int hours;
  5. int minutes;
  6.  
  7. // Default constructor
  8. Clock() {
  9. this.hours = 0;
  10. this.minutes = 0;
  11. }
  12.  
  13. // Constructor with 1 argument
  14. Clock(int h) {
  15. setTime(h, 0);
  16. }
  17.  
  18. // Constructor with 2 argument
  19. Clock(int h, int m) {
  20. setTime(h, m);
  21. }
  22.  
  23. // Instance methods
  24. int getHour() {
  25. return this.hours;
  26. }
  27.  
  28. int getMinute() {
  29. return this.minutes;
  30. }
  31.  
  32. void incrementTimer() {
  33. if (this.minutes < 59) {
  34. this.minutes += 1;
  35. }
  36. else {
  37. this.minutes += 1;
  38. this.hours += 1;
  39. this.minutes = 0;
  40. }
  41.  
  42. }
  43.  
  44. void incrementTimer(int x) {
  45. for (int i = 0; i < x; i++) {
  46. incrementTimer();
  47. }
  48. }
  49.  
  50. void setTime(int h, int m) {
  51. if ((h >= 0 && h <= 24) && (m >= 0 && m <= 59)) {
  52. this.hours = h;
  53. this.minutes = m;
  54. }
  55. else if ((h > 24 || m > 60)||(h > 24 && m > 60)) {
  56. System.out.println("Invalid Input");
  57. }
  58. }
  59.  
  60. public String toString() {
  61. String hs = String.valueOf(hours);
  62. String ms = String.valueOf(minutes);
  63. String time = "";
  64. String sm = ":";
  65.  
  66. if(hs.length() == 1) {
  67. hs = "12";
  68. }
  69. if(hs.length() == 1) {
  70. hs = "0" + hs;
  71.  
  72. }
  73. if(minutes <= 9) {
  74. ms = "0" + ms;
  75. }
  76. if(hours < 12) {
  77. time = " AM";
  78. }
  79. else {
  80. time = " PM";
  81. }
  82. if(hours > 12 && hours < 21) {
  83. hs = "0"+ String.valueOf(hours-12);
  84. }
  85. else if (hours > 24){
  86. hs = String.valueOf(hours-12);
  87.  
  88. }
  89. return hs + sm + ms + time;
  90. }
  91.  
  92. }
Advertisement
Add Comment
Please, Sign In to add comment