Implement a class Clock . Whose job it is to return the current time in UTC (Coo
ID: 3910414 • Letter: I
Question
Implement a class Clock. Whose job it is to return the current time in UTC (Coordinated Universal Time).
Clock should have three public methods:
getHours - which returns the current hour as an int.
getMinutes - which returns the current minute as an int.
getTime - which returns, as a string the full time (concatenating the results of getHours and getMinutes).
The getHours and getMinutes methods should work by invoking java.time.Instant.now().toString() and then extract the relevant portion of that string to figure out what to return.
Next, provide another class WorldClock that is a subclass of Clock. The constructor for WorldClass will accept a time offset. For example, new WorldClock(-4) should show the time in currently in New York since we are currently on EDT which 4 hours behind UTC. To do this you will need to override one of the three methods listed above. You must not override getTime.
You’ve been provided with a ClockTester.java that shows some example use cases of the two classes. As well as an empty Clock.java and WorldClock.java.
Explanation / Answer
Given below is the code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you
Clock.java
-----
import java.time.Instant;
public class Clock {
public Clock() {
}
public int getHours(){
String s = Instant.now().toString();
//example value in s is 2018-06-28T22:53:12.023Z
int index = s.indexOf('T'); //get index of T
s = s.substring(index+1); //get substring after T
String[] parts = s.split(":"); //using : as delimiter break it up
//the first part is hours
return Integer.parseInt(parts[0]);
}
public int getMinutes(){
String s = Instant.now().toString();
//example value in s is 2018-06-28T22:53:12.023Z
int index = s.indexOf('T'); //get index of T
s = s.substring(index+1); //get substring after T
String[] parts = s.split(":"); //using : as delimiter break it up
//the second part is minutes
return Integer.parseInt(parts[1]);
}
public String getTime(){
return String.format("%02d:%02d", getHours(), getMinutes());//format as hh:mm
}
}
WorldClock.java
---------
public class WorldClock extends Clock {
private int offsetHours;
public WorldClock(int offset) {
offsetHours = offset;
}
@Override
public int getHours() {
int hours = super.getHours() + offsetHours;
if(hours < 0)
hours += 24;
else if(hours >= 24)
hours -= 24;
return hours;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.