Spaces:
Running
Running
| The program defines the class Clock, | |
| which has the following operations that are useful for the solution: | |
| method hours() which RETURNS the clock's hours as an integer | |
| method minutes() which RETURNS the clock's minutes as an integer | |
| method setTime(String time), which a time can be set in the format "hh.mm", example "15.45" | |
| The program also defines 3 Clock-type variables: | |
| realTime, which according to its name is set to the correct time | |
| clock1 and clock2, which are in the wrong time | |
| Your task is to set clocks 1 and 2 to the correct time using the methods described above. | |
| import java.util.Random; | |
| public class Test { | |
| public static void main(String[] args) { | |
| final Random random = new Random(); | |
| int hours = random.nextInt(13) + 10; | |
| int minutes = random.nextInt(49) + 10; | |
| Clock realTime = new Clock(hours, minutes); | |
| System.out.println("Correct time: " + realTime); | |
| Clock clock1 = new Clock(1, 1); | |
| Clock clock2 = new Clock(1, 1); | |
| //ADD | |
| clock1.setTime(realTime.hours()+"."+realTime.minutes()); | |
| clock2.setTime(realTime.hours()+"."+realTime.minutes()); | |
| System.out.println("Clock 1: " + clock1); | |
| System.out.println("Clock 2: " + clock2); | |
| } | |
| } | |
| class Clock { | |
| private int hours; | |
| private int minutes; | |
| public Clock(int hours, int minutes) { | |
| this.hours = hours; | |
| this.minutes = minutes; | |
| } | |
| // METHOD1 | |
| public int hours() { | |
| return hours; | |
| } | |
| // METHOD2 | |
| public int minutes() { | |
| return minutes; | |
| } | |
| // METHOD3 | |
| public void setTime(String time) { | |
| String[] parts = time.split("\\."); | |
| this.hours = Integer.valueOf(parts[0]); | |
| this.minutes = Integer.valueOf(parts[1]); | |
| } | |
| public String toString() { | |
| return hours + "." + minutes; | |
| } | |
| } | |
| Correct time: 18.36 | |
| Clock 1: 18.36 | |
| Clock 2: 18.36 | |