KaiquanMah commited on
Commit
e3fb21c
·
verified ·
1 Parent(s): 224e6b2

Create 02B. Set the clocks to the correct time

Browse files
Week 4: Writing classes/02B. Set the clocks to the correct time ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ The program defines the class Clock,
2
+ which has the following operations that are useful for the solution:
3
+ method hours() which RETURNS the clock's hours as an integer
4
+ method minutes() which RETURNS the clock's minutes as an integer
5
+ method setTime(String time), which a time can be set in the format "hh.mm", example "15.45"
6
+
7
+
8
+
9
+ The program also defines 3 Clock-type variables:
10
+ realTime, which according to its name is set to the correct time
11
+ clock1 and clock2, which are in the wrong time
12
+
13
+
14
+ Your task is to set clocks 1 and 2 to the correct time using the methods described above.
15
+
16
+
17
+
18
+
19
+
20
+
21
+ import java.util.Random;
22
+
23
+ public class Test {
24
+ public static void main(String[] args) {
25
+ final Random random = new Random();
26
+
27
+
28
+ int hours = random.nextInt(13) + 10;
29
+ int minutes = random.nextInt(49) + 10;
30
+ Clock realTime = new Clock(hours, minutes);
31
+
32
+ System.out.println("Correct time: " + realTime);
33
+
34
+ Clock clock1 = new Clock(1, 1);
35
+ Clock clock2 = new Clock(1, 1);
36
+
37
+
38
+ //ADD
39
+ clock1.setTime(realTime.hours()+"."+realTime.minutes());
40
+ clock2.setTime(realTime.hours()+"."+realTime.minutes());
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+ System.out.println("Clock 1: " + clock1);
51
+ System.out.println("Clock 2: " + clock2);
52
+ }
53
+ }
54
+
55
+ class Clock {
56
+ private int hours;
57
+ private int minutes;
58
+
59
+ public Clock(int hours, int minutes) {
60
+ this.hours = hours;
61
+ this.minutes = minutes;
62
+ }
63
+
64
+ // METHOD1
65
+ public int hours() {
66
+ return hours;
67
+ }
68
+
69
+ // METHOD2
70
+ public int minutes() {
71
+ return minutes;
72
+ }
73
+
74
+ // METHOD3
75
+ public void setTime(String time) {
76
+ String[] parts = time.split("\\.");
77
+ this.hours = Integer.valueOf(parts[0]);
78
+ this.minutes = Integer.valueOf(parts[1]);
79
+ }
80
+
81
+ public String toString() {
82
+ return hours + "." + minutes;
83
+ }
84
+ }
85
+
86
+
87
+
88
+
89
+
90
+
91
+
92
+ Correct time: 18.36
93
+ Clock 1: 18.36
94
+ Clock 2: 18.36
95
+
96
+