Java Reference
In-Depth Information
1
// Fig. 8.1: Time1.java
2
// Time1 class declaration maintains the time in 24-hour format.
3
4
public class Time1
5
{
6
private int hour; // 0 - 23
private int minute; // 0 - 59
private int second; // 0 - 59
7
8
9
10
// set a new time value using universal time; throw an
11
// exception if the hour, minute or second is invalid
12
public void setTime( int hour, int minute, int second)
13
{
14
// validate hour, minute and second
15
if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 ||
16
second < 0 || second >= 60 )
17
{
18
throw new IllegalArgumentException(
"hour, minute and/or second was out of range" );
19
20
}
21
22
this .hour = hour;
23
this .minute = minute;
24
this .second = second;
25
}
26
27
// convert to String in universal-time format (HH:MM:SS)
28
public String toUniversalString()
29
{
30
return String.format( "%02d:%02d:%02d" , hour, minute, second);
31
}
32
33
// convert to String in standard-time format (H:MM:SS AM or PM)
34
public String toString()
35
{
36
return String.format( "%d:%02d:%02d %s" ,
((hour == 0 || hour == 12 ) ? 12 : hour % 12 ),
minute, second, (hour < 12 ? "AM" : "PM" ));
37
38
39
}
40
} // end class Time1
Fig. 8.1 | Time1 class declaration maintains the time in 24-hour format.
Default Constructor
In this example, class Time1 does not declare a constructor, so the compiler supplies a de-
fault constructor. Each instance variable implicitly receives the default int value. Instance
variables also can be initialized when they're declared in the class body, using the same ini-
tialization syntax as with a local variable.
Method setTime and Throwing Exceptions
Method setTime (lines 12-25) is a public method that declares three int parameters and
uses them to set the time. Lines 15-16 test each argument to determine whether the value
is outside the proper range. The hour value must be greater than or equal to 0 and less than
 
Search WWH ::




Custom Search