Java Reference
In-Depth Information
30
public int bookRoom ( boolean smoking )
31
{
32
int begin, end, roomNumber=0;
33
34
if ( !smoking )
35
{
36
begin = 0;
37
end = numNonSmoking;
38
}
39
else
40
{
41
begin = numNonSmoking;
42
end = numSmoking+numNonSmoking;
43
}
44
45
for ( int i=begin; i<end; ++i )
46
{
47
if ( !occupied [ i ]) //if room is not occupied
48
{
49
occupied [ i ] = true ;
50
roomNumber = i+1;
51
i = end; //to exit loop
52
}
53
}
54
return roomNumber;
55
}
56 }
FIGURE 5-15
The bookRoom() method must evaluate each of the desired type of rooms
(nonsmoking or smoking), one by one, looking for an unoccupied room (a false
element in the array). In the body of the bookRoom() method, three variables
are declared: one that will hold the first room to be evaluated, one that will hold
the last room to be evaluated, and one that will hold the reserved room number,
once it is identified.
An if statement in line 34 determines whether the driver class has asked for a
smoking or nonsmoking room. If a nonsmoking room has been requested, the
rooms to be evaluated will begin at zero, as stored in a variable named begin in
line 36. The evaluation will continue through the total number of nonsmoking
rooms (as previously stored by the Rooms() constructor method and assigned to
the NonSmoking variable), which is stored in a variable named end (line 37).
Otherwise, the bookRoom() method will begin looking at the first smoking
room (assigned in line 41) and proceed to the end of the array (calculated and
assigned in line 42).
The for loop in lines 45 through 53 goes through the appropriate rooms
looking for an unoccupied one. A false value in the boolean array indicates an
unoccupied room; if an unoccupied room is found, its value is changed to true
in line 49. The room number is assigned and the for loop exits. If the for loop
completes without finding an unoccupied room, the initial roomNumber value
of zero, previously initialized in line 32, is returned to the calling program
indicating that all rooms of that type are full (line 54).
Search WWH ::




Custom Search