07B Static & Enum


Classwork -- Must be done in pairs, due in class!

Correct answers will only use concepts and constructs we have covered in class.


Part A

Create an enumeration AptType representing several different types of apartment in a building. Each type of apartment has a description, a square footage, and a rent amount. In the enumeration, provide final instance variables for these. Also write a parameterized constructor that sets the values of these variables. The apartment types are

description size (sq ft) rent ($/mo)
"Studio" 520 480
"1 Bedroom" 810 720
"2 Bedroom" 1120 1030
"Penthouse" 1720 1780

Create the possible values for the enumeration, one for each type of apartment, using constructor calls to set their instance variables. Give these brief all-caps names.


Part B

Create a class Apartment. Each Apartment has an apartment type (use your enumeration), and a boolean indicating whether it is rented or not. Apartments should start off unrented.

To the Apartment class, add a static variable building, which is a 2-dimensional array of Apartments.

Add a public constant int FLOORS, which is 4, and another APTSPERFLOOR, which is 10.

In a static initializer block, set up building to be FLOORS x APTSPERFLOOR apartments in size (4 floors, 10 apartments on each), and fill in all the apartments so that there is a floor full of each type of apartment.

In doing this, use the .values() method of the enumeration to get the appropriate type of apartment for the appropriate floor without having to use a conditional.  (Hint: if all the studio apartments are on floor 0, and STUDIO is the 0th item in the enumeration . . . )

Add a static method rent(floor, num) which, if the apartment at that position in building is currently free, sets it as rented and (using the values from AptType) prints a message like

You are renting a 1120 square foot 2 Bedroom apartment for $1030 / month.  Welcome to our building.

If the apartment is already rented, print an apologetic message saying the apartment is taken.

If the number requested is not valid in building (e.g., 5th floor) print an error message.


Part C

In a class with a main, in a loop randomly choose 10 apartments (i.e. random number for floor and apartment) from the building and try to rent them. Do this without creating any instances of Apartment in this class.