Next: The switch statement Up: Unit 05 Previous: A class to handle

## Solution of the exercise on the class TimeOfDay

```public class TimeOfDay {

// we represent a time of the day by the total number of seconds since midnight
private int totsec;

public TimeOfDay(int h, int m, int s) {
totsec = h*3600 + m*60 + s;
}

this.totsec += t.totsec;
if (this.totsec > 24*3600)
this.totsec -= 24*3600;
}

public void subtract(TimeOfDay t) {
this.totsec -= t.totsec;
if (this.totsec < 0)
this.totsec += 24*3600;
}

public boolean precedes(TimeOfDay t) {
return this.totsec < t.totsec;
}

public boolean equalTo(TimeOfDay t) {
return this.totsec == t.totsec;
}

public String toString() {
int h = totsec / 3600;
int m = (totsec - h*3600) / 60;
int s = (totsec - h*3600 - m*60);
String hh = (h < 10) ? " " + h : Integer.toString(h);
String mm = (m < 10) ? " " + m : Integer.toString(m);
String ss = (s < 10) ? " " + s : Integer.toString(s);
return hh + ":" + mm + ":" + ss;
}
}
```

Next: The switch statement Up: Unit 05 Previous: A class to handle