SlideShare a Scribd company logo
1 of 7
Download to read offline
CMPSC 221 
Object-Oriented Programming with Web Applications 
Spring 2011 
Exam I: Object-Oriented Programming 
February 17, 2011 
Name: SOLUTION Last 4 digits of ID: ____ ____ ____ ____ 
I certify that I have not discussed the contents of the exam with any other student and I will not 
discuss the contents of this exam with any student in this class before it is returned to me with a 
grade. I have not cheated on this exam in any way, nor do I know of anyone else who has cheated. 
Signature: _________________________________________________________ 
Directions/Notes: 
Honor Code Statement 
• Write your ID on every page of this exam. Write your name just on this cover page. 
• No notes, books, or calculators are permitted. 
• Be sure to sign the honor code statement when you are finished. 
• Answer each conceptual question completely, clearly, and concisely. 
• 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). 
• The points intentionally add up to more than 100 possible. 
Score Breakdown: 
Problem Page 2 
Conceptual 
Page 3 
Conceptual 
Problem 1 Problem 2 Problem 3 Total 
Score 
Value 20 20 5 23 35 100
CMPSC 221 / Spring 2011 / Exam 1 - Page 2 of 7 
Last 4 Digits of Student ID Number: ___ ___ ___ ___ 
Part I: Conceptual Questions [40 points] 
1. Static members. [6 pts.] 
a. What does it mean for a member of a class to be static? 
A static member is independent of objects/instances of the class (or it is shared among all instances). 
b. Contrast and justify programming practices for initializing static and non-static data members within a class. 
Non-static (instance) data members are initialized in constructors. Meanwhile, as static members are independent of 
objects, they're initialized in the class data dictionary. 
c. Compare and contrast how static and non-static methods are called outside of a class. 
Non-static (instance) methods are called using dot notation on the name of an object, whereas static methods are 
calling using dot notation on the name of the class. 
2. How does composition help facilitate encapsulation? [4 pts.] 
Composition is the idea of using classes together (using has-a relationships). If we use several classes to solve a 
problem, those classes would naturally be smaller than if we had used one larger class. This facilitates encapsulation, as 
the classes created are more focused on more closely related data and behavior. (Encapsulation is keeping related data 
and behavior in the same place.) 
3. Consider the inheritance hierarchy shown at right. Each part of this question is independent. [10 pts.] 
a. In which class(es) would it make most sense to have protected members? Which class(es) would be able to 
access those protected members directly? 
Since A and C have subclasses, it would make sense for them to have 
protected members (as protected members can be accessed directly in the 
class where they're created and in subclasses of that class). 
The protected members of A could be accessed in A, B, C, D, and E. 
The protected members of C could be accessed in C, D, and E. 
b. Which class(es) can access private members of class C directly? 
Any private members of C could only be accessed in C, as private 
members can only be accessed directly in the class which defines them. 
A 
B C 
D E 
c. Suppose class C contains an abstract method. Suppose we wish to instantiate objects of this hierarchy. Which 
class(es) are or could be abstract and which are concrete? 
Since C has an abstract method, C must be abstract, and since C is the child of A and C is abstract, A must be 
abstract. The other classes would need to be concrete so that we could instantiate objects in this hierarchy. 
d. Suppose class A is the only abstract class in the hierarchy. Discuss why this code will or will not work: 
A[] collectionA = new A[20]; 
collectionA[3] = new D(); 
The first line makes an array of type A. It's possible to make an array of type A, even though A is abstract. (But 
it's not possible to put an A object in this array, because we can't instantiate an abstract class.) The second line is 
fine; it attempts to instantiate a concrete class, which is possible and desirable, and it attempts to put it an A 
container, which is possible since D is a kind of A. So, this code works just fine. 
e. Suppose class A is the only abstract class in the hierarchy. Discuss why this code will or will not work: 
C[] collectionC = new C[20]; 
collectionA[7] = new B(); 
The first line makes an array of type C. It's possible to make this array. The second line attempts to instantiate a 
concrete class, B, which is possible. However, it fails in its attempt to put a B in a C container, which is impossible 
because B is not a subclass of C.
CMPSC 221 / Spring 2011 / Exam 1 - Page 3 of 7 
Last 4 Digits of Student ID Number: ___ ___ ___ ___ 
4. Consider the code below. Interpret it. Will it work? Why or why not? [3 pts.] 
public class Z extends Y, X implements W, V 
This attempts to make a class which is a subclass of two parent classes, which would be multiple inheritance. Java 
doesn't support multiple inheritance, so this code won't work. Java does allow implementing multiple interfaces, which 
the last clause correctly tries to do. 
5. What are the three kinds of member functions of a class? [3 pts.] 
constructor, modifier, accessor 
6. Why don't we care about destructors in Java? [2 pts.] 
Java has automatic garbage collection that takes care of this for us. 
7. Give the command necessary to compile the file in which the class FloorLamp is implemented. [2 pts.] 
javac FloorLamp.java 
8. How are data members that tagged final in Java different from constants in C++? [2 pts.] 
A C++ constant must be initialized at declaration, whereas a Java final data member can be initialized separately. 
9. Consider the following list of classes: Car, SteeringWheel, Vehicle, Van, Minivan, AudioSystem, 
ParkingLot. Your task is to describe all of the is-a and has-a relationships between these classes. Include an 
inheritance hierarchy for all classes that fit. Present your response as clearly as possible and justify your choices (and any 
interpretations you feel it necessary to clarify). [8 pts.] 
See the inheritance hierarchy to the right. It shows the things that are 
different types of the same concept. Cars, vans, and minivans are 
specific types of vehicles and a minivan is a specific type of van. So, 
• Car is-a Vehicle 
• Van is-a Vehicle 
• Minivan is-a Van 
• Minivan is-a Vehicle 
None of the other entities are kinds of vehicles, so they're not in the 
hierarchy. Instead, it's believable any type of vehicle has a steering 
wheel and audio system. Thus, 
• Vehicle has-a SteeringWheel 
and, in turn, 
• Car has-a SteeringWheel 
• Van has-a SteeringWheel 
• Minivan has-a SteeringWheel 
Likewise, 
• Vehicle has-a AudioSystem 
and, in turn, 
• Car has-a AudioSystem 
• Van has-a AudioSystem 
• Minivan has-a AudioSystem. 
Finally, a parking lot would be a container for vehicles, so 
• ParkingLot has-a Vehicle 
and, in turn, 
• ParkingLot has-a Car 
• ParkingLot has-a Van 
• ParkingLot has-a Minivan 
Vehicle 
Car Van 
Minivan 
Alternatively, if we read each entry in this table as 
[row heading] ______ [column heading], 
then: 
Vehicle Car Van Minivan Steering Audio Parking 
Wheel System Lot 
Vehicle --- --- --- --- has-a has-a --- 
Car is-a --- --- --- has-a has-a --- 
Van is-a --- --- --- has-a has-a --- 
Minivan is-a --- is-a --- has-a has-a --- 
SteeringWheel --- --- --- --- --- --- --- 
AudioSystem --- --- --- --- --- --- --- 
ParkingLot has-a has-a has-a has-a --- --- ---
CMPSC 221 / Spring 2011 / Exam 1 - Page 4 of 7 
Last 4 Digits of Student ID Number: ___ ___ ___ ___ 
Part II: Programming Problems [60 points] 
1. Suppose we have a fully-populated array of VideoGameEnemy objects (as in Lab 5 with a proper toString()) 
called enemies. We want to walk this array and print all details of all enemies to screen. [5 pts.] 
a. Explain the logic you'd use to decide which kind of loop ideally solves this problem. 
The first decision to consider in any "which loop to use" problem is whether the situation is determinate or not. 
Here, we're walking an array and we know exactly how many iterations the loop would run before executing the 
loop (5). Next, we note that we have no need for the indices of the array, so the enhanced for loop is best. 
b. Now write that loop to solve this problem. 
for(VideoGameEnemy vge : enemies) 
{ 
System.out.println(vge); 
} 
2. Suppose have a class called CoordinateList2D and it has the following already defined: [23 pts.] 
private double[] xPts; // x coordinates on Cartesian plane 
private double[] yPts; // y coordinates on Cartesian plane, parallel to xPts 
private int ct; // number of values in xPts and yPts 
public void populateFromFile(String filename) 
// PRE: filename denotes a file in the CLASSPATH directory formatted with two numeric 
// quantities per line separated by whitespace 
// POST: All lines of the file given by filename, and data is stored into xPts and yPts such 
// that for line i, xPts[i] and yPts[i] are populated, overwriting any previous data. 
// ct is set the number of points. 
public void scaleUp(double factor) 
// PRE: factor > 1 
// POST: All values in xPts[0..(ct-1)] and yPts[0..(ct-1)] are factor times larger than they 
// were prior to the call 
a. Implement a default constructor for CoordinateList2D. [3 pts.] 
// Best practice is to add a constant, e.g. MAX_SIZE, for the array's physical size 
public CoordinateList2D() 
{ 
xPts = new double[MAX_SIZE]; 
yPts = new double[MAX_SIZE]; 
ct = 0; 
} 
b. Working in CoordinateList2D, implement a method addPoint that takes as inputs an x and y coordinate and 
adds them to the end of xPts and yPts. [5 pts.] 
public void addPoint(double x, double y) 
{ 
xPts[ct] = x; 
yPts[ct] = y; 
ct++; 
} 
Note: This question solves a similar problem to that of keeping track of a player's properties in Monopoly or reading in 
several data points in Lab 1. (The difference is that we bring in parallel arrays.) In any event, the strategy is always 
the same: initially allocate an array to a physical size that's large enough to hold as much or more data you 
anticipate, initialize a logical size to 0, insert at the logical size, and increment the logical size at that point.
CMPSC 221 / Spring 2011 / Exam 1 - Page 5 of 7 
Last 4 Digits of Student ID Number: ___ ___ ___ ___ 
c. Working in CoordinateList2D, implement either a toString() that lists all pairs of points as ordered pairs 
with 2 decimal places and with line breaks between each point. For up to 5 points, instead implement display(), 
which will just print these values to the console with the same formatting. [8 pts.] 
public String toString() 
{ 
String result = ""; 
for(int i = 0; i < ct; i++) 
{ 
result += String.format("(%.2f, %.2f)n", xPts[i], yPts[i]); 
} 
return result; 
} 
d. Now, suppose you're writing a main in a client and you want to write a user program to get a filename for data and 
a factor by which to enlarge the data, and then print the result to screen. Use a CoordinateList2D object to do 
this. Prompt the user for inputs, displaying error messages for scale factors that don't make sense or would violate 
any preconditions, and then display the scaled results. [7 pts.] 
CoordinateList2D list; 
String file; 
double scale; 
try 
{ 
System.out.print("Enter filename: "); 
file = input.next(); 
System.out.print("Enter positive scale factor: "); 
scale = input.nextDouble(); 
list = new CoordinateList2D(); 
list.populateFromFile(file); 
if(scale <= 1) 
{ 
System.out.print("Scale factor must be larger than 1. Try again."); 
} 
else 
{ 
list.scaleUp(scale); 
System.out.print("Scaled Points: " + list); 
} 
} 
catch(InputMismatchException ime) 
{ 
System.out.println("Scale factor must be a number. Try again."); 
} 
This question was about using a CoordinateList2D object (3 points) and knowing when to use error handling 
and exception handling (4 points). Credit was awarded here for the following key things, each a point: 
• Calling the populateFromFile on an object (which requires that you've first constructed an object). 
• Checking that the scale factor met the precondition of scaleUp. 
• Giving an error message for the above, telling the user how to resolve the problem. 
• Checking that the scale factor entered was numeric via exception handling. 
• Giving an error message for the above, telling the user how to resolve the problem. 
• Calling scaleUp on the object (which requires that you've first constructed an object). 
• Display the scaled list using the object (which requires that you've first constructed an object). 
All of the other details didn't necessarily affect your grade, except that credit was deducted for things that definitely 
didn't work or for extremely poor practices like haphazardly declaring variables in the middle of logic.
CMPSC 221 / Spring 2011 / Exam 1 - Page 6 of 7 
Last 4 Digits of Student ID Number: ___ ___ ___ ___ 
3. Mini Golf: Suppose you've been hired to help build the Objectville (virtual, of course) miniature golf course and you're 
working on defining obstacles, e.g. stones, windmills, moving characters, sand traps, water traps, etc. [35 pts. total] 
You'll start with a class called Obstacle, which has the following data dictionary: 
protected String description; // phrase telling what the obstacle is and what it looks like 
protected boolean isElectronic; // whether obstacle needs power to operate (true) or not (false) 
protected int strokePenalty; // number of strokes a player whose ball stops on/in this 
// obstacle suffers 
You also have at your disposal the following constructor: 
public Obstacle(String description, boolean isElectronic, int strokePenalty) 
// PRE: description and isElectronic are initialized and strokePenalty >= 0 
// POST: An Obstacle is constructed with data fields description, isElectronic, and 
// strokePenalty set to the corresponding parameters 
a. Create a default constructor for the Obstacle class. You decide what the default obstacle is. [5 pts.] 
public Obstacle() 
{ 
this("Large rock", false, 0); 
} 
b. One kind of an obstacle we'll have is called a Shuffler, which is a circular object that could be decorated in various 
ways and designed to be placed on a course at a place where it might be advantageous for the ball's path to change. 
They don't harm the player's score directly, but it's possible to have the Shuffler greatly help or hurt one's progress. If 
a player's ball enters a Shuffler, it is spun around using a motor inside, and randomly projected outward some other 
direction. (See illustration at the bottom of the next page.) Due to the physical limitations of building such a piece of 
equipment, a Shuffler is only capable of directing a golf ball at angles of 0, 15, 30, 45, ..., 345 degrees clockwise 
from where the golf ball entered and any of these angles is equally likely. Shufflers can be programmed such that 
there is a minimum and maximum angle allowed. You'll implement this with a subclass of Obstacle called 
Shuffler, which has the following additional data members: 
private int minAngle; // smallest angle in degrees, with respect to entry point, 
// ball could be directed 
private int maxAngle; // largest angle in degrees, with respect to entry point, 
// ball could be directed 
First, write the first line of the class definition for Shuffler. [2 pts.] 
public class Shuffler extends Obstacle 
c. Given this information, write an initializer constructor that allows initialization of all configurable properties of a 
Shuffler. [6 pts.] 
public Shuffler(String details, int minAngle, int maxAngle) 
{ 
super("Shuffler " + details, true, 0); // build description, these things need power, 
// and don't directly harm scores 
this.minAngle = minAngle; // set the new properties 
this.maxAngle = maxAngle; 
} 
d. Write a precondition for the method from (c). [4 pts.] 
// PRE: details is a description of this shuffler and could grammatically 
// follow "Shuffler." 
// 0 < minAngle < maxAngle and both minAngle and maxAngle are in degrees 
// and are exact multiples of 15 
This problem continues on the next page...
CMPSC 221 / Spring 2011 / Exam 1 - Page 7 of 7 
Last 4 Digits of Student ID Number: ___ ___ ___ ___ 
e. Use the information from (b) to implement the following Shuffler member function: [9 pts.] 
public int getNewAngle() 
// POST: FCTVAL == the random angle a ball that enters this Shuffler will exit it, in degrees 
{ 
int numAnglesPossible; // number of possible angles ball could be redirected 
int outcomeNum; // random number of outcome between 0 and 
// numAnglesPossible, inclusive 
int resultAngle; // exit angle in degrees w.r.t. entry angle 
numAnglesPossible = (maxAngle-minAngle)/15; // only allowed to use every 15th 
// degree, so find how many 
outcomeNum = (int)(Math.random()*(numAnglesPossible+1)); // allow for lowest case or most 
// (needing +1 as random() 
// never gives exactly 1) 
resultAngle = minAngle + 15*outcomeNum; // scale back to multiples of 15 
return resultAngle; 
} 
f. Suppose you're working in client code now. Create and initialize an array to hold three obstacles that are found on 
Hole #9 (below): a water trap that causes a one-stroke penalty, a Shuffler that is painted bright orange and which can 
redirect balls at angles of 15 to 210 degrees clockwise, and whatever you've decided the default obstacle is. [5 pts.] 
Obstacle[] hole9Obstacles = new Obsacle[3]; 
hole9Obstacles[0] = new Obstacle("Water Trap", false, 1); 
hole9Obstacles[1] = new Shuffler("colored bright orange", 15, 210); 
hole9Obstacles[2] = new Obstacle(); 
g. Write a line of code to display a message you'd display to the console* to tell the user that his/her ball entered the 
Shuffler from your array in (f) and the direction it's now headed after exiting. [4 pts.] 
System.out.println("Your ball entered the Shuffler as has been redirected by " 
+ ((Shuffler) hole9Obstacles[1]).getNewAngle() + " degrees."); 
Just a rock (my default), but placed just 
so it's in the way if you're in this corner 
The Shuffler that could send you almost back to start, to 
the water (oh no!), or angle you toward the goal 
Water trap 
* No, I wouldn't think you'd write a text-based golf game, although there's a certain nostalgic charm to the idea and I'm imagining a lot of interesting ASCII art.

More Related Content

What's hot

Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceEng Teong Cheah
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsAnil Kumar
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
E3
E3E3
E3lksoo
 
java tr.docx
java tr.docxjava tr.docx
java tr.docxharishkuna4
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oopsHirra Sultan
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend classAbhishek Wadhwa
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismJawad Khan
 
Object as function argument , friend and static function by shahzad younas
Object as function argument , friend and static function by shahzad younasObject as function argument , friend and static function by shahzad younas
Object as function argument , friend and static function by shahzad younasShahzad Younas
 
Inheritance
InheritanceInheritance
InheritanceLoy Calazan
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingArslan Waseem
 

What's hot (20)

Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
 
Chapter 3
Chapter 3Chapter 3
Chapter 3
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Friend functions
Friend functions Friend functions
Friend functions
 
Inheritance
InheritanceInheritance
Inheritance
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
E3
E3E3
E3
 
java tr.docx
java tr.docxjava tr.docx
java tr.docx
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Inheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphismInheritance, friend function, virtual function, polymorphism
Inheritance, friend function, virtual function, polymorphism
 
Object as function argument , friend and static function by shahzad younas
Object as function argument , friend and static function by shahzad younasObject as function argument , friend and static function by shahzad younas
Object as function argument , friend and static function by shahzad younas
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Inheritance, Object Oriented Programming
Inheritance, Object Oriented ProgrammingInheritance, Object Oriented Programming
Inheritance, Object Oriented Programming
 
Inheritance
InheritanceInheritance
Inheritance
 
Friend function in c++
Friend function in c++ Friend function in c++
Friend function in c++
 

Similar to E4

Advanced software engineering lab 2
Advanced software engineering lab 2Advanced software engineering lab 2
Advanced software engineering lab 2asimnawaz54
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1stConnex
 
Bt8903, c# programming
Bt8903, c# programmingBt8903, c# programming
Bt8903, c# programmingsmumbahelp
 
Exercise1[5points]Create the following classe
Exercise1[5points]Create the following classeExercise1[5points]Create the following classe
Exercise1[5points]Create the following classemecklenburgstrelitzh
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comKeatonJennings91
 
Delphi qa
Delphi qaDelphi qa
Delphi qasandy14234
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questionsnicolbiden
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examplesbindur87
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS ConceptRicha Gupta
 
Ppl home assignment_unit3
Ppl home assignment_unit3Ppl home assignment_unit3
Ppl home assignment_unit3Akshay Nagpurkar
 
Devry CIS 247 Full Course Latest
Devry CIS 247 Full Course LatestDevry CIS 247 Full Course Latest
Devry CIS 247 Full Course LatestAtifkhilji
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesTabassumMaktum
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2Mukul kumar Neal
 

Similar to E4 (20)

Advanced software engineering lab 2
Advanced software engineering lab 2Advanced software engineering lab 2
Advanced software engineering lab 2
 
Presentation 1st
Presentation 1stPresentation 1st
Presentation 1st
 
Oops ppt
Oops pptOops ppt
Oops ppt
 
Bt8903, c# programming
Bt8903, c# programmingBt8903, c# programming
Bt8903, c# programming
 
Exercise1[5points]Create the following classe
Exercise1[5points]Create the following classeExercise1[5points]Create the following classe
Exercise1[5points]Create the following classe
 
CIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.comCIS 407 STUDY Inspiring Innovation--cis407study.com
CIS 407 STUDY Inspiring Innovation--cis407study.com
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
Core java notes with examples
Core java notes with examplesCore java notes with examples
Core java notes with examples
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
17515
1751517515
17515
 
Ppl home assignment_unit3
Ppl home assignment_unit3Ppl home assignment_unit3
Ppl home assignment_unit3
 
Devry CIS 247 Full Course Latest
Devry CIS 247 Full Course LatestDevry CIS 247 Full Course Latest
Devry CIS 247 Full Course Latest
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Java mcq
Java mcqJava mcq
Java mcq
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
 

More from lksoo

Lo48
Lo48Lo48
Lo48lksoo
 
Lo43
Lo43Lo43
Lo43lksoo
 
Lo39
Lo39Lo39
Lo39lksoo
 
Lo37
Lo37Lo37
Lo37lksoo
 
Lo27
Lo27Lo27
Lo27lksoo
 
Lo17
Lo17Lo17
Lo17lksoo
 
Lo12
Lo12Lo12
Lo12lksoo
 
T3
T3T3
T3lksoo
 
T2
T2T2
T2lksoo
 
T1
T1T1
T1lksoo
 
T4
T4T4
T4lksoo
 
P5
P5P5
P5lksoo
 
P4
P4P4
P4lksoo
 
P3
P3P3
P3lksoo
 
P1
P1P1
P1lksoo
 
P2
P2P2
P2lksoo
 
L10
L10L10
L10lksoo
 
L9
L9L9
L9lksoo
 
L8
L8L8
L8lksoo
 
L7
L7L7
L7lksoo
 

More from lksoo (20)

Lo48
Lo48Lo48
Lo48
 
Lo43
Lo43Lo43
Lo43
 
Lo39
Lo39Lo39
Lo39
 
Lo37
Lo37Lo37
Lo37
 
Lo27
Lo27Lo27
Lo27
 
Lo17
Lo17Lo17
Lo17
 
Lo12
Lo12Lo12
Lo12
 
T3
T3T3
T3
 
T2
T2T2
T2
 
T1
T1T1
T1
 
T4
T4T4
T4
 
P5
P5P5
P5
 
P4
P4P4
P4
 
P3
P3P3
P3
 
P1
P1P1
P1
 
P2
P2P2
P2
 
L10
L10L10
L10
 
L9
L9L9
L9
 
L8
L8L8
L8
 
L7
L7L7
L7
 

Recently uploaded

The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 

Recently uploaded (20)

9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 

E4

  • 1. CMPSC 221 Object-Oriented Programming with Web Applications Spring 2011 Exam I: Object-Oriented Programming February 17, 2011 Name: SOLUTION Last 4 digits of ID: ____ ____ ____ ____ I certify that I have not discussed the contents of the exam with any other student and I will not discuss the contents of this exam with any student in this class before it is returned to me with a grade. I have not cheated on this exam in any way, nor do I know of anyone else who has cheated. Signature: _________________________________________________________ Directions/Notes: Honor Code Statement • Write your ID on every page of this exam. Write your name just on this cover page. • No notes, books, or calculators are permitted. • Be sure to sign the honor code statement when you are finished. • Answer each conceptual question completely, clearly, and concisely. • 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). • The points intentionally add up to more than 100 possible. Score Breakdown: Problem Page 2 Conceptual Page 3 Conceptual Problem 1 Problem 2 Problem 3 Total Score Value 20 20 5 23 35 100
  • 2. CMPSC 221 / Spring 2011 / Exam 1 - Page 2 of 7 Last 4 Digits of Student ID Number: ___ ___ ___ ___ Part I: Conceptual Questions [40 points] 1. Static members. [6 pts.] a. What does it mean for a member of a class to be static? A static member is independent of objects/instances of the class (or it is shared among all instances). b. Contrast and justify programming practices for initializing static and non-static data members within a class. Non-static (instance) data members are initialized in constructors. Meanwhile, as static members are independent of objects, they're initialized in the class data dictionary. c. Compare and contrast how static and non-static methods are called outside of a class. Non-static (instance) methods are called using dot notation on the name of an object, whereas static methods are calling using dot notation on the name of the class. 2. How does composition help facilitate encapsulation? [4 pts.] Composition is the idea of using classes together (using has-a relationships). If we use several classes to solve a problem, those classes would naturally be smaller than if we had used one larger class. This facilitates encapsulation, as the classes created are more focused on more closely related data and behavior. (Encapsulation is keeping related data and behavior in the same place.) 3. Consider the inheritance hierarchy shown at right. Each part of this question is independent. [10 pts.] a. In which class(es) would it make most sense to have protected members? Which class(es) would be able to access those protected members directly? Since A and C have subclasses, it would make sense for them to have protected members (as protected members can be accessed directly in the class where they're created and in subclasses of that class). The protected members of A could be accessed in A, B, C, D, and E. The protected members of C could be accessed in C, D, and E. b. Which class(es) can access private members of class C directly? Any private members of C could only be accessed in C, as private members can only be accessed directly in the class which defines them. A B C D E c. Suppose class C contains an abstract method. Suppose we wish to instantiate objects of this hierarchy. Which class(es) are or could be abstract and which are concrete? Since C has an abstract method, C must be abstract, and since C is the child of A and C is abstract, A must be abstract. The other classes would need to be concrete so that we could instantiate objects in this hierarchy. d. Suppose class A is the only abstract class in the hierarchy. Discuss why this code will or will not work: A[] collectionA = new A[20]; collectionA[3] = new D(); The first line makes an array of type A. It's possible to make an array of type A, even though A is abstract. (But it's not possible to put an A object in this array, because we can't instantiate an abstract class.) The second line is fine; it attempts to instantiate a concrete class, which is possible and desirable, and it attempts to put it an A container, which is possible since D is a kind of A. So, this code works just fine. e. Suppose class A is the only abstract class in the hierarchy. Discuss why this code will or will not work: C[] collectionC = new C[20]; collectionA[7] = new B(); The first line makes an array of type C. It's possible to make this array. The second line attempts to instantiate a concrete class, B, which is possible. However, it fails in its attempt to put a B in a C container, which is impossible because B is not a subclass of C.
  • 3. CMPSC 221 / Spring 2011 / Exam 1 - Page 3 of 7 Last 4 Digits of Student ID Number: ___ ___ ___ ___ 4. Consider the code below. Interpret it. Will it work? Why or why not? [3 pts.] public class Z extends Y, X implements W, V This attempts to make a class which is a subclass of two parent classes, which would be multiple inheritance. Java doesn't support multiple inheritance, so this code won't work. Java does allow implementing multiple interfaces, which the last clause correctly tries to do. 5. What are the three kinds of member functions of a class? [3 pts.] constructor, modifier, accessor 6. Why don't we care about destructors in Java? [2 pts.] Java has automatic garbage collection that takes care of this for us. 7. Give the command necessary to compile the file in which the class FloorLamp is implemented. [2 pts.] javac FloorLamp.java 8. How are data members that tagged final in Java different from constants in C++? [2 pts.] A C++ constant must be initialized at declaration, whereas a Java final data member can be initialized separately. 9. Consider the following list of classes: Car, SteeringWheel, Vehicle, Van, Minivan, AudioSystem, ParkingLot. Your task is to describe all of the is-a and has-a relationships between these classes. Include an inheritance hierarchy for all classes that fit. Present your response as clearly as possible and justify your choices (and any interpretations you feel it necessary to clarify). [8 pts.] See the inheritance hierarchy to the right. It shows the things that are different types of the same concept. Cars, vans, and minivans are specific types of vehicles and a minivan is a specific type of van. So, • Car is-a Vehicle • Van is-a Vehicle • Minivan is-a Van • Minivan is-a Vehicle None of the other entities are kinds of vehicles, so they're not in the hierarchy. Instead, it's believable any type of vehicle has a steering wheel and audio system. Thus, • Vehicle has-a SteeringWheel and, in turn, • Car has-a SteeringWheel • Van has-a SteeringWheel • Minivan has-a SteeringWheel Likewise, • Vehicle has-a AudioSystem and, in turn, • Car has-a AudioSystem • Van has-a AudioSystem • Minivan has-a AudioSystem. Finally, a parking lot would be a container for vehicles, so • ParkingLot has-a Vehicle and, in turn, • ParkingLot has-a Car • ParkingLot has-a Van • ParkingLot has-a Minivan Vehicle Car Van Minivan Alternatively, if we read each entry in this table as [row heading] ______ [column heading], then: Vehicle Car Van Minivan Steering Audio Parking Wheel System Lot Vehicle --- --- --- --- has-a has-a --- Car is-a --- --- --- has-a has-a --- Van is-a --- --- --- has-a has-a --- Minivan is-a --- is-a --- has-a has-a --- SteeringWheel --- --- --- --- --- --- --- AudioSystem --- --- --- --- --- --- --- ParkingLot has-a has-a has-a has-a --- --- ---
  • 4. CMPSC 221 / Spring 2011 / Exam 1 - Page 4 of 7 Last 4 Digits of Student ID Number: ___ ___ ___ ___ Part II: Programming Problems [60 points] 1. Suppose we have a fully-populated array of VideoGameEnemy objects (as in Lab 5 with a proper toString()) called enemies. We want to walk this array and print all details of all enemies to screen. [5 pts.] a. Explain the logic you'd use to decide which kind of loop ideally solves this problem. The first decision to consider in any "which loop to use" problem is whether the situation is determinate or not. Here, we're walking an array and we know exactly how many iterations the loop would run before executing the loop (5). Next, we note that we have no need for the indices of the array, so the enhanced for loop is best. b. Now write that loop to solve this problem. for(VideoGameEnemy vge : enemies) { System.out.println(vge); } 2. Suppose have a class called CoordinateList2D and it has the following already defined: [23 pts.] private double[] xPts; // x coordinates on Cartesian plane private double[] yPts; // y coordinates on Cartesian plane, parallel to xPts private int ct; // number of values in xPts and yPts public void populateFromFile(String filename) // PRE: filename denotes a file in the CLASSPATH directory formatted with two numeric // quantities per line separated by whitespace // POST: All lines of the file given by filename, and data is stored into xPts and yPts such // that for line i, xPts[i] and yPts[i] are populated, overwriting any previous data. // ct is set the number of points. public void scaleUp(double factor) // PRE: factor > 1 // POST: All values in xPts[0..(ct-1)] and yPts[0..(ct-1)] are factor times larger than they // were prior to the call a. Implement a default constructor for CoordinateList2D. [3 pts.] // Best practice is to add a constant, e.g. MAX_SIZE, for the array's physical size public CoordinateList2D() { xPts = new double[MAX_SIZE]; yPts = new double[MAX_SIZE]; ct = 0; } b. Working in CoordinateList2D, implement a method addPoint that takes as inputs an x and y coordinate and adds them to the end of xPts and yPts. [5 pts.] public void addPoint(double x, double y) { xPts[ct] = x; yPts[ct] = y; ct++; } Note: This question solves a similar problem to that of keeping track of a player's properties in Monopoly or reading in several data points in Lab 1. (The difference is that we bring in parallel arrays.) In any event, the strategy is always the same: initially allocate an array to a physical size that's large enough to hold as much or more data you anticipate, initialize a logical size to 0, insert at the logical size, and increment the logical size at that point.
  • 5. CMPSC 221 / Spring 2011 / Exam 1 - Page 5 of 7 Last 4 Digits of Student ID Number: ___ ___ ___ ___ c. Working in CoordinateList2D, implement either a toString() that lists all pairs of points as ordered pairs with 2 decimal places and with line breaks between each point. For up to 5 points, instead implement display(), which will just print these values to the console with the same formatting. [8 pts.] public String toString() { String result = ""; for(int i = 0; i < ct; i++) { result += String.format("(%.2f, %.2f)n", xPts[i], yPts[i]); } return result; } d. Now, suppose you're writing a main in a client and you want to write a user program to get a filename for data and a factor by which to enlarge the data, and then print the result to screen. Use a CoordinateList2D object to do this. Prompt the user for inputs, displaying error messages for scale factors that don't make sense or would violate any preconditions, and then display the scaled results. [7 pts.] CoordinateList2D list; String file; double scale; try { System.out.print("Enter filename: "); file = input.next(); System.out.print("Enter positive scale factor: "); scale = input.nextDouble(); list = new CoordinateList2D(); list.populateFromFile(file); if(scale <= 1) { System.out.print("Scale factor must be larger than 1. Try again."); } else { list.scaleUp(scale); System.out.print("Scaled Points: " + list); } } catch(InputMismatchException ime) { System.out.println("Scale factor must be a number. Try again."); } This question was about using a CoordinateList2D object (3 points) and knowing when to use error handling and exception handling (4 points). Credit was awarded here for the following key things, each a point: • Calling the populateFromFile on an object (which requires that you've first constructed an object). • Checking that the scale factor met the precondition of scaleUp. • Giving an error message for the above, telling the user how to resolve the problem. • Checking that the scale factor entered was numeric via exception handling. • Giving an error message for the above, telling the user how to resolve the problem. • Calling scaleUp on the object (which requires that you've first constructed an object). • Display the scaled list using the object (which requires that you've first constructed an object). All of the other details didn't necessarily affect your grade, except that credit was deducted for things that definitely didn't work or for extremely poor practices like haphazardly declaring variables in the middle of logic.
  • 6. CMPSC 221 / Spring 2011 / Exam 1 - Page 6 of 7 Last 4 Digits of Student ID Number: ___ ___ ___ ___ 3. Mini Golf: Suppose you've been hired to help build the Objectville (virtual, of course) miniature golf course and you're working on defining obstacles, e.g. stones, windmills, moving characters, sand traps, water traps, etc. [35 pts. total] You'll start with a class called Obstacle, which has the following data dictionary: protected String description; // phrase telling what the obstacle is and what it looks like protected boolean isElectronic; // whether obstacle needs power to operate (true) or not (false) protected int strokePenalty; // number of strokes a player whose ball stops on/in this // obstacle suffers You also have at your disposal the following constructor: public Obstacle(String description, boolean isElectronic, int strokePenalty) // PRE: description and isElectronic are initialized and strokePenalty >= 0 // POST: An Obstacle is constructed with data fields description, isElectronic, and // strokePenalty set to the corresponding parameters a. Create a default constructor for the Obstacle class. You decide what the default obstacle is. [5 pts.] public Obstacle() { this("Large rock", false, 0); } b. One kind of an obstacle we'll have is called a Shuffler, which is a circular object that could be decorated in various ways and designed to be placed on a course at a place where it might be advantageous for the ball's path to change. They don't harm the player's score directly, but it's possible to have the Shuffler greatly help or hurt one's progress. If a player's ball enters a Shuffler, it is spun around using a motor inside, and randomly projected outward some other direction. (See illustration at the bottom of the next page.) Due to the physical limitations of building such a piece of equipment, a Shuffler is only capable of directing a golf ball at angles of 0, 15, 30, 45, ..., 345 degrees clockwise from where the golf ball entered and any of these angles is equally likely. Shufflers can be programmed such that there is a minimum and maximum angle allowed. You'll implement this with a subclass of Obstacle called Shuffler, which has the following additional data members: private int minAngle; // smallest angle in degrees, with respect to entry point, // ball could be directed private int maxAngle; // largest angle in degrees, with respect to entry point, // ball could be directed First, write the first line of the class definition for Shuffler. [2 pts.] public class Shuffler extends Obstacle c. Given this information, write an initializer constructor that allows initialization of all configurable properties of a Shuffler. [6 pts.] public Shuffler(String details, int minAngle, int maxAngle) { super("Shuffler " + details, true, 0); // build description, these things need power, // and don't directly harm scores this.minAngle = minAngle; // set the new properties this.maxAngle = maxAngle; } d. Write a precondition for the method from (c). [4 pts.] // PRE: details is a description of this shuffler and could grammatically // follow "Shuffler." // 0 < minAngle < maxAngle and both minAngle and maxAngle are in degrees // and are exact multiples of 15 This problem continues on the next page...
  • 7. CMPSC 221 / Spring 2011 / Exam 1 - Page 7 of 7 Last 4 Digits of Student ID Number: ___ ___ ___ ___ e. Use the information from (b) to implement the following Shuffler member function: [9 pts.] public int getNewAngle() // POST: FCTVAL == the random angle a ball that enters this Shuffler will exit it, in degrees { int numAnglesPossible; // number of possible angles ball could be redirected int outcomeNum; // random number of outcome between 0 and // numAnglesPossible, inclusive int resultAngle; // exit angle in degrees w.r.t. entry angle numAnglesPossible = (maxAngle-minAngle)/15; // only allowed to use every 15th // degree, so find how many outcomeNum = (int)(Math.random()*(numAnglesPossible+1)); // allow for lowest case or most // (needing +1 as random() // never gives exactly 1) resultAngle = minAngle + 15*outcomeNum; // scale back to multiples of 15 return resultAngle; } f. Suppose you're working in client code now. Create and initialize an array to hold three obstacles that are found on Hole #9 (below): a water trap that causes a one-stroke penalty, a Shuffler that is painted bright orange and which can redirect balls at angles of 15 to 210 degrees clockwise, and whatever you've decided the default obstacle is. [5 pts.] Obstacle[] hole9Obstacles = new Obsacle[3]; hole9Obstacles[0] = new Obstacle("Water Trap", false, 1); hole9Obstacles[1] = new Shuffler("colored bright orange", 15, 210); hole9Obstacles[2] = new Obstacle(); g. Write a line of code to display a message you'd display to the console* to tell the user that his/her ball entered the Shuffler from your array in (f) and the direction it's now headed after exiting. [4 pts.] System.out.println("Your ball entered the Shuffler as has been redirected by " + ((Shuffler) hole9Obstacles[1]).getNewAngle() + " degrees."); Just a rock (my default), but placed just so it's in the way if you're in this corner The Shuffler that could send you almost back to start, to the water (oh no!), or angle you toward the goal Water trap * No, I wouldn't think you'd write a text-based golf game, although there's a certain nostalgic charm to the idea and I'm imagining a lot of interesting ASCII art.