Java Reference
In-Depth Information
The fields would have been auto-initialized to
0
anyway, but many programmers
prefer to explicitly initialize field values for clarity.
Another useful operation for
TimeSpan
objects is the ability to print them on the
console. We'll add this ability by including a
toString
method that returns a
String
such as
"2h 35m"
for 2 hours and 35 minutes.
Here is the code for the complete
TimeSpan
class that enforces its invariant:
1 // Represents a time span of hours and minutes elapsed.
2 // Class invariant: hours >= 0 && minutes >= 0 && minutes < 60
3
4
public class
TimeSpan {
5
private int
hours;
6
private int
minutes;
7
8 // Constructs a time span with the given interval.
9 // pre: hours >= 0 && minutes >= 0
10
public
TimeSpan(
int
hours,
int
minutes) {
11
this
.hours = 0;
12
this
.minutes = 0;
13 add(hours, minutes);
14 }
15
16 // Adds the given interval to this time span.
17 // pre: hours >= 0 && minutes >= 0
18
public void
add(
int
hours,
int
minutes) {
19
if
(hours < 0 || minutes < 0) {
20
throw new
IllegalArgumentException();
21 }
22
23
this
.hours += hours;
24
this
.minutes += minutes;
25
26 // converts each 60 minutes into one hour
27
this
.hours += this.minutes / 60;
28
this
.minutes = this.minutes % 60;
29 }
30
31 // returns a String for this time span, such as "6h 15m"
32
public
String toString() {
33
return
hours + "h " + minutes + "m";
34 }
35 }
Search WWH ::
Custom Search