Beruflich Dokumente
Kultur Dokumente
Directions/Notes:
Write your ID on every page of this exam. Write your name just on this cover page.
Be sure to sign the honor code statement when you are finished.
All questions on this exam are implicitly prefaced with As taught in CMPSC 221 lectures this
term.
In coding problems, you may assume all import statements needed have been provided and you
may always assume you have in scope a properly-initialized Scanner object called input to
read from the console.
No comments are required in coding problems unless explicitly required. They may be added to
clarify assumptions (as long as assumptions don't circumvent the problems at hand).
Score Breakdown:
#
10
11
12
13
Total
11
39
100
Score
Value
1.
Suppose we have a block of code that contains the possibility there's a file that won't be found, a division by zero, any
kind of input/output problem, and an uninitialized reference variable. List the exceptions you must catch in an
appropriate order and explain why you chose the order you did.
[4 pts.]
We must catch more specific exceptions before more general exceptions because only the first catch block that "fits" is
executed.
Thus, we must catch FileNotFoundFoundException before IOException because the former is a subclass of
the latter and we must catch Exception at the end because it is the most general kind of exception.
Exceptions ArithmeticException and NullPointerException fit in anywhere else
(Day 12 / Lab 9)
2.
[3 pts.]
Overriding occurs when we have a method in a superclass and we implement a method with the same name and
parameters in a subclass to do something more specific in the subclass. Overloading occurs when we make a second
method with the same name as an existing method within the same class, but with a different parameter list. (The
odd caveat: we could, in a subclass, overload a method that's in a superclass as long as we've not overridden it.)
(Day 6)
3.
[3 pts.]
This would be appropriate if we have a method we wanted subclasses to be able to use, but not clients. Such a need
would arise if we wanted to make a method for some common computation used in subclasses to aid other
computations and which is independent of the specific subclass. (Day 6 and beyond)
4.
[2 pts.]
Java has a built-in automatic garbage collector that cleans up any unused dynamically-allocated objects. (Day 4)
5.
Explain how it would be possible to make an array containing a BankAccount, the integer 7, and a Trapezoid or
explain why it's not possible.
[3 pts.]
Since BankAccount and Trapezoid are reference type variables, they both inherit from Object, so they could
easily be stored in an array of type Object. The integer, if stored in an int, could not, because int is a primitive
type. However, we could get around this problem by storing the 7 in the wrapper class Integer, which is a
reference type, enabling us to store all of these rather unrelated things in an array of type Object. (Day 6, 2)
6.
7.
b.
encapsulation - keeping related data and behavior in the same place (Day 4)
The bytecode verifier is the part of the JVM responsible for making sure a program doesn't cause
security violations. (Day 1)
b.
The kind of class member function that changes the state of objects is modifiers. (Day 4)
c.
Allowing a class to inherit from more than one superclass is called multiple inheritance. (Day 9)
[4 pts.]
[3 pts.]
8.
Consider the following list of classes that model parts of a programming language's syntax: CodeBlock,
ControlStructure, Switch, ForLoop, WhileLoop, SelectionStructure, LoopTest,
RepetitionStructure, IfElseBlock, UpdateStep. A CodeBlock is defined as the code that could be in
the body of any method; the meanings of the rest should be obvious from your programming experience. Your task is to
describe all of the is-a and has-a relationships between these classes.
[9 pts.]
a.
IfElseBlock
b.
RepetitionStructure
Switch
ForLoop
WhileLoop
Then fill in this chart, where the header of each row would begin each relationship and the header of each column
would end each relationship. Thus, if you believed the statement CodeBlock is a ControlStructure were
true, you'd write "is a" in the second column of the first row. Each block should say "is a" or "has a" or be left blank
if there is no relationship.
CodeBlock
Code
Block
Control
Structure
Switch
For
Loop
While
Loop
Selection
Structure
--
has a
has a
has a
has a
has a
Control
Structure
--
Switch
is a
ForLoop
is a
WhileLoop
is a
Selection
Structure
is a
--
Repetition
Structure
IfElse
Block
has a
has a
Update
Step
is a
--
--
has a
is a
has a
has a
is a
has a
--
has a
--
--
LoopTest
Repetition
Structure
is a
IfElse
Block
is a
UpdateStep
Loop
Test
has a
is a
--
--
It could also be argued that any ControlStructure has a CodeBlock in the body, so has a relationships would
be accepted for credit.
(Day 5, 6, 7, 8)
9.
Implement this function used to determine the winner of a contest from an array of entries:
[6 pts.]
10. Suppose you have three perfectly parallel arrays that store the food and supplies a catering company orders during a
typical week:
String[] products;
int[] quantities;
double[] unitCosts;
These arrays store quantities for a typical week, but events during different seasons change the sales demand for the
company. Suppose, then, we also have a constant, EXPECTED_EXPENDITURES, that tells how much money (in
dollars) the manager expects to spend during a given week on ordering food and supplies. Assume that the when the
company has a higher sales week, it simply multiplies its order proportionally. For example, if during a typical week the
company spends $50 on plastic silverware and $100 on paper plates, it would spend $75 on plastic silverware and $150
on paper plates during a week when its expected expenditures were 1.5 times the normal amount.
Assuming that all three parallel arrays have been filled and are of the same size, initialize a fourth parallel array of type
int called quantitiesToOrder such that it contains how many of the corresponding product to order to get the
total amount spent as close to EXPECTED_EXPENDITURES as possible without ever going over budget (thus you
should always round down).
[8 pts.]
double sum;
double multiplier;
11. Suppose we have abstract class BigCat, which has concrete subclasses Lion, Tiger, and Panther. Suppose we
have the following array:
BigCat[] cats = new BigCat[10];
Element 0 of cats is a Lion, element 1 is a Tiger, and element 2 is a Panther.
[11 pts.]
a.
Suppose there's an abstract method attack() defined in BigCat. Write a block of code to send a message to all
of the initialized elements of cats to attack.
for(BigCat cat : cats)
{
cat.attack();
}
b.
It is due to polymorphism that each BigCat has the ability to attack in a different way and due to dynamic binding
that the correct form of attack() happens for the correct BigCat when the code of part (a) executes.
c.
d.
Suppose class Lion has a method roar() that only exists in Lion, not any of the other subclasses. Send a
message to the Lion at position 0 in cats to roar.
((Lion) cats[0]).roar();
(Day 8 and your experience having to typecast with abstract classes in Project 1.)
12. Suppose class TVChannel models TV channels and has accessor getName() that returns the name of the TV channel
stored in each object. Suppose we have the following array:
TVChannel[] majorNetworks;
Suppose majorNetworks is full, i.e. every element contains meaningful data.
[9 pts.]
a.
Write a block of code that stores a comma-separated list of the names of the channels in majorNetworks in a
String variable channelNames.
channelNames = "";
for(int i = 0; i < majorNetworks.length; i++)
{
channelNames += majorNetworks[i].getName();
b.
(Part (a) was to be exactly the same thing as the comma-separated list in the Player class in the Project and Part (b)
comes from the whole review unit.)
13. Suppose were are modeling a parking lot and have a class ParkingLot to do this. To help us out, we have a class
called ParkedVehicle, which is used to model vehicles that could park in the lot.
[39 pts.]
Suppose class ParkingLot contains the following data members:
private int numSpacesTotal;
a.
Write a reasonable default constructor for the ParkingLot class. (Remember, no documentation - internal or
external - is required on this exam unless a problem explicitly requests it.)
[5 pts.]
public ParkingLot()
{
numSpacesTotal = 100;
numSpacesUsed = 0;
carsInLot = new ParkedVehicle[numSpacesTotal];
}
b.
Write a method removeVehicleAtIndex(), which takes as an input parameter an index to the array
carsInLot and which adjusts carsInLot such that the vehicle at the input index is effectively removed from
carsInLot, as per documentation of the class data members in the class data dictionary above.
[6 pts.]
public void removeVehicleAtIndex(int index)
// PRE: 0 <= index < numSpacesUsed
// POST: carsInLot[index..(numSpacesUsed-2)] contain what
//
carsInLot[(index+1)..(numSpacesUsed-1)] before the call,
//
and numSpacesUsed is one smaller than before the call
{
for(int i = index; i < numSpacesUsed-1; i++)
{
carsInLot[i] = carsInLot[i+1];
}
numSpacesUsed--;
(Day 4)
c.
Write the header for an initializer constructor that takes as input parameters any number of ParkedVehicle
objects that have been initialized and are in the lot as well as the capacity of the lot.
[2 pts.]
public ParkingLot(int capacity, ParkedVehicle... vehicles)
(Day 3)
Now suppose we want to consider a subclass of ParkingLot to model parking lots that charge parking fees. We'll call
this class PaidParkingLot.
d. Add whatever is necessary to complete the first line of code of the class definition of PaidParkingLot:
public class PaidParkingLot extends ParkingLot
e.
(Day 6)
Define a data member for the parking lot's hourly rate as you'd add it to the data dictionary of PaidParkingLot.
(This one requires documentation.)
[3 pts.]
private double hourlyRate;
f.
[2 pts.]
(Day 4)
Suppose we mandated that once a parking lot's hourly rate were set, it could not change. How would your response
to (e) change?
[1 pt.]
Make it final
(Day 5)
Suppose that all PaidParkingLots are owned by the same company, and this company sometimes gives
discounted holiday rates. Define a data member as you'd add it to the data dictionary of PaidParkingLot, that
indicates whether or not it is a holiday. (The definition is not necessary this time.)
[3 pts.]
(Day 5)
h.
Suppose PaidParkingLot has a method turnHolidayRateOn() that essentially sets the data member you
defined in the last part to true. Suppose for this part only that you are working in client code and you have two
PaidParkingLots, beaverAveLot and fraserStLot. Write appropriate code to turn the holiday rate on for
both of these lots.
[3 pts.]
(Day 5)
PaidParkingLot.turnHolidayRateOn();
i.
Write an initializer constructor for PaidParkingLot that takes two input parameters: the parking lot's hourly rate
and how many spaces are in the lot.
[7 pts.]
public PaidParkingLot(double hourlyRate, int capacity)
{
super();
numSpacesTotal = capacity;
carsInLot = new ParkedVehicle[numSpacesTotal];
this.hourlyRate = hourlyRate;
h.
(Day 6)
[3 pts.]
// PRE:
//
i.