# help with clock class

• February 22nd, 2010, 06:06 PM
collinsislee
help with clock class
i missed lecture today and we were supposed to complete this class and objects. im not really sure how to do this and would appreciate any help you all can provide.
Code :

```class Clock { // Declare fields of the class // 0 <= hours < 24, 0 <= minutes < 60, 0 <= seconds < 60 private int hours, minutes, seconds; Clock(int hh, int mm, int ss) //constructor { } //increase time by sec seconds public void incrementSeconds(int sec) { } //increase time by min minutes public void incrementMinutes(int min) { } //increase time by hh hours, //if hours reach 24, simply wrap around to 0. public void incrementHours(int hh) { } public void addTime(Clock C) //add C into the clock { } //print time in hours:minutes:seconds am(or pm) format public void printTime() { } } class ClockDemo { public static void main(String [] args) { //write each statement for each operation below (create Clock object C1 with h:m:s = 0:0:0) (create second Clock object C2 with h:m:s=12:35:59) (add C2 into C1) (print C1) (print C2) (increase clock C1 by 1 seconds) (print C1) (increase clock C1 by 100 minutes) (print C1) (increase clock C1 by 10 hours) (print C1) (print C2) } }```
• February 24th, 2010, 01:53 PM
CT&SC
Re: help with clock class
Well the incrementing shouldn't be too bad.

If you incremented by n seconds, then as long as n >= 60, increment by minutes instead and subtract 60 from n. When 0 <= n < 60, add that to the current number of seconds. If the result is >= 60, subtract 60 and increment minutes again.

Ditto for minutes & hours.

For hours, just subtract 24 from n until 0 <= n < 24, and then add that to hours. If the result >= 24, subtract 24.

There are more efficient ways to do this involving integer division and modulus operators, but loops are easy and none of this is going to be expensive.

The stuff in main() you should really have no trouble with.