-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClock.java
More file actions
82 lines (69 loc) · 2.71 KB
/
Copy pathClock.java
File metadata and controls
82 lines (69 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* *****************************************************************************
* Name: Ada Lovelace
* Coursera User ID: 123456
* Last modified: October 16, 1842
**************************************************************************** */
public class Clock {
private int hour, min;
// Creates a clock whose initial time is h hours and m minutes.
public Clock(int h, int m) {
if (h < 0 || h > 23)
throw new IllegalArgumentException("hour must be between 0 and 23");
if (m < 0 || m > 59)
throw new IllegalArgumentException("min must be between 0 and 59");
hour = h;
min = m;
}
// Creates a clock whose initial time is specified as a string, using the format HH:MM.
public Clock(String s) {
int indexOfcolon = s.indexOf(':');
if (indexOfcolon != 2)
throw new IllegalArgumentException("format should be HH:MM ");
String hr = s.substring(0, indexOfcolon);
String m = s.substring(indexOfcolon + 1);
if (m.length() != 2)
throw new IllegalArgumentException("format should be HH:MM ");
hour = Integer.parseInt(hr);
min = Integer.parseInt(m);
if (hour < 0 || hour > 23)
throw new IllegalArgumentException("hour must be between 0 and 23");
if (min < 0 || min > 59)
throw new IllegalArgumentException("min must be between 0 and 59");
}
// Returns a string representation of this clock, using the format HH:MM.
public String toString() {
String h = String.valueOf(hour);
String m = String.valueOf(min);
if (h.length() == 1) h = "0" + h;
if (m.length() == 1) m = "0" + m;
return h + ":" + m;
}
// Is the time on this clock earlier than the time on that one?
public boolean isEarlierThan(Clock that) {
int t1 = hour * 60 + min;
int t2 = that.hour * 60 + that.min;
if (t2 > t1) return true;
return false;
}
// Adds 1 minute to the time on this clock.
public void tic() {
hour = (hour + (min + 1) / 60) % 24;
min = (min + 1) % 60;
}
// Adds Δ minutes to the time on this clock.
public void toc(int delta) {
if (delta < 0)
throw new IllegalArgumentException("delta should be positive");
hour = (hour + (min + delta) / 60) % 24;
min = (min + delta) % 60;
}
public static void main(String[] args) {
Clock clock1 = new Clock(2, 59);
Clock clock2 = new Clock("03:30");
System.out.println(clock1.isEarlierThan(clock2));
clock1.tic();
System.out.println(clock1);
clock2.toc(50);
System.out.println(clock2);
}
}