Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170706;
- /*
- *Clock class
- *
- *Classes, Exercise 01, slide 46
- */
- public class Clock {
- // properties
- private int hours; // hours : 0 to 23
- private int minutes; // minutes : 0 to 59
- private int seconds; // seconds : 0 to 59
- // return hours property
- public int getHours() {
- return hours;
- }
- // set hours property
- // return true on success, false otherwise
- public boolean setHours(int hours) {
- // if invalid argument
- if (hours < 0 || hours > 23) {
- // do nothing and return false
- return false;
- }
- // update hours and return true for success
- this.hours = hours;
- return true;
- }
- // return minutes property
- public int getMinutes() {
- return minutes;
- }
- // set minutes property
- // return true on success, false otherwise
- public boolean setMinutes(int minutes) {
- // if invalid argument
- if (minutes < 0 || minutes > 59) {
- // do nothing and return false
- return false;
- }
- // update minutes and return true for success
- this.minutes = minutes;
- return true;
- }
- // return seconds property
- public int getSeconds() {
- return seconds;
- }
- // set seconds property
- // return true on success, false otherwise
- public boolean setSeconds(int seconds) {
- // if invalid argument
- if (seconds < 0 || seconds > 59) {
- // do nothing and return false
- return false;
- }
- // update seconds and return true for success
- this.seconds = seconds;
- return true;
- }
- // increase the time by one second
- public void tick() {
- this.seconds += 1;
- if (this.seconds == 60) {
- this.seconds = 0;
- this.minutes += 1;
- if (this.minutes == 60) {
- this.minutes = 0;
- this.hours += 1;
- if (this.hours == 24) {
- this.hours = 0;
- }
- }
- }
- }
- // print a the clock on the screen as hh:mm:ss
- public void show() {
- System.out.printf("%02d:%02d:%02d", this.hours, this.minutes,
- this.seconds);
- }
- // reset the clock to 00:00:00
- public void reset() {
- this.hours = this.minutes = this.seconds = 0;
- }
- @Override
- public String toString() {
- return String.format("%02d:%02d:%02d", this.hours, this.minutes,
- this.seconds);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement