Programming Logic and Design Sample Assignment

Programming Exercises

a. Design a class named Circle with fields named radius, area, and diameter. Include a constructor that sets the radius to 1. Include get methods for each field, but include a set method only for the radius. When the radius is set, do not allow it to be zero or a negative number. When the radius is set, calculate the diameter (twice the radius) and the area (the radius squared times pi, which is approximately 3.14). Create the class diagram and write the pseudocode that defines the class.

Diagram:

Pseudocode:

class Circle

Declarations

private num area

private num diameter

public Circle()

return

else

endif

return

public num getArea()

return area

public num getDiameter()

return diameter

endClass

b. Design an application that declares two Circles. Set the radius of one manually, but allow the other to use the default value supplied by the constructor. Then, display each Circleâ€™s values.

Pseudocode:

start

Declarations

Circle myCircle

Circle yourCircle

output â€śCircle 1 info:â€ť

output myCircle.getArea()

output myCircle.getDiameter()

output â€śCircle 2 info:â€ť

output yourCircle.getArea()

output yourCircle.getDiameter()

stop

a. Design a class named PhoneCall with four fields: two strings that hold the 10-digit phone numbers that originated and received the call, and two numeric fields that hold the length of the call in minutes and the cost of the call. Include a constructor that sets the phone numbers to Xs and the numeric fields to 0. Include get and set methods for the phone number and call length fields, but do not include a set method for the cost field. When the call length is set, calculate the cost of the call at three cents per minute for the first 10 minutes, and two cents per subsequent minute. Create the class diagram and write the pseudocode that defines the class.

Diagram:

 PhoneCall -origCall: string -recCall: string -length: num -cost: num +setOrigCall(number : string) : void +setRecCall(number : string) : void +setLength(len : num) : void +getOrigCall() : string +getRecCall() : string +getLength() : num +getCost() : num

Pseudocode:

class PhoneCall

Declarations

private string origCall

private string recCall

private num length

private num cost

public PhoneCall()

origCall = â€śXXXXXXXXXXâ€ť

recCall = â€śXXXXXXXXXXâ€ť

length = 0

cost = 0

return

public void setOrigCall(string number)

origCall = number

return

public void setRecCall(string number)

recCall = number

return

public void setLength(num len)

length = len

if length > 10 then

cost = (3 * 10) + (2 * (length â€“ 10))

else

cost = 3 * length

endif

return

public string getOrigCall()

return origCall

public string getRecCall()

return recCall

public num getLength()

return length

public num getCost()

return cost

endClass

b. Design an application that declares three PhoneCalls. Set the length of one PhoneCall to 10 minutes, another to 11 minutes, and allow the third object to use the default value supplied by the constructor. Then, display each PhoneCallâ€™s values.

Pseudocode:

start

Declarations

PhoneCall callOne

PhoneCall callTwo

PhoneCall callThree

callOne.setLength(10)

callTwo.setLength(11)

output â€śPhoneCall 1 info:â€ť

output â€śOriginating number = â€ť, callOne.getOrigCall()

output â€śReceiving number = â€ť, callOne.getRecCall()

output â€śCall length = â€ť, callOne.getLength()

output â€śCall cost = â€ť, callOne.getCost()

output â€śPhoneCall 2 info:â€ť

output â€śOriginating number = â€ť, callTwo.getOrigCall()

output â€śReceiving number = â€ť, callTwo.getRecCall()

output â€śCall length = â€ť, callTwo.getLength()

output â€śCall cost = â€ť, callTwo.getCost()

output â€śPhoneCall 3 info:â€ť

output â€śOriginating number = â€ť,

callThree.getOrigCall()

output â€śReceiving number = â€ť, callThree.getRecCall()

output â€śCall length = â€ť, callThree.getLength()

output â€śCall cost = â€ť, callThree.getCost()

stop

c. Create a child class named InternationalPhoneCall. Override the parent class method that sets the call length to calculate the cost of the call at 40 cents per minute.

Diagram:

 PhoneCall -origCall: string -recCall: string -length: num -cost: num +setOrigCall(number : string) : void +setRecCall(number : string) : void +setLength(len : num) : void +getOrigCall() : string +getRecCall() : string +getLength() : num +getCost() : num

 InternationalPhoneCall +setLength(len : num) : void

Pseudocode:

class InternationPhoneCall inheritsFrom PhoneCall

public void setLength(num len)

length = len

cost = length * 40

return

endClass

d. Create the logic for an application that instantiates a PhoneCall object and an InternationalPhoneCall object and displays the costs for both.

Pseudocode:

start

Declarations

PhoneCall myCall

InternationalPhoneCall yourCall

myCall.setLength(15)

yourCall.setLength(14)

output â€śPhoneCall cost:â€ť

output myCall.getCost()

output â€śInternationalPhoneCall cost:â€ť

output yourCall.getCost()

stop

3. Assigned

a. Create a class named Meal that includes a string variable for the mealâ€™s description, an array of strings that holds up to five of the Mealâ€™s components (for example, â€śroasted chickenâ€ť, â€śmashed potatoesâ€ť, and â€śgreen beansâ€ť), and a numeric variable that holds the calorie count. Include a method that prompts the user for a value for each field. Also create two overloaded methods named display(). The first method takes no parameters and displays the Meal details. The second takes a numeric parameter that indicates how many of the Mealâ€™s components to display, or an error message if the parameter value is less than 0 or more than 5.

Diagram:

(the student may or may not provide get and set methods)

 Meal -description: string -components: string[] -calories: num +setValues() : void +display() : void +display(numOfComps : num) : void

Pseudocode:

class Meal

Declarations

private string description

private string components[5]

private num calories

public void setValues()

Declarations

num x = 0

output â€śEnter a description >> â€ť

input description

while x < 5

output â€śEnter a meal component >> â€ť

input components[x]

x = x + 1

endwhile

output â€śEnter the number of calories >> â€ť

input calories

return

public void display()

Declarations

num x = 0

output â€śDescription: â€ť, description

output â€śComponents: â€ť

while x < 5

output x + 1, â€ś. â€ť, components[x]

x = x + 1

endwhile

output â€śNumber of calories: â€ť, calories

return

public void display(num numOfComps)

Declarations

num x = 0

if (x => 0 AND x <= 5) then

output â€śDescription: â€ť, description

output â€śComponents: â€ť

while x < numOfComps

output x + 1, â€ś. â€ť, components[x]

x = x + 1

endwhile

output â€śNumber of calories: â€ť, calories

else

output â€śInvalid number of componentsâ€ť

endif

return

endClass

b. Create an application that declares two Meal objects and demonstrates how both method versions can be called.

Pseudocode:

start

Declarations

Meal lunch

Meal dinner

lunch.setValues()

dinner.setValues()

output â€śCalling display() with no args:â€ť

lunch.display()

output â€śCalling display() with 1 arg:â€ť

dinner.display(3)

stop

a. Create a class named Trip that includes four string variables: destination (for example, â€śLondonâ€ť), means of transportation (for example, â€śairâ€ť), departure date (for example, â€ś12/15/2015â€ť), and tripâ€™s purpose (for example, â€śbusinessâ€ť). Include two overloaded constructors. The default constructor sets each field to â€śXXXâ€ť. The nondefault constructor accepts four parametersâ€”one for each field. Include two overloaded display() methods. The parameterless version displays all the Trip details. The second version accepts a string that represents a destination and displays the Trip details only if the Tripâ€™s destination matches the parameter.

Diagram:

(the student may or may not provide get and set methods)

 Trip -destination: string -meansOfTransport: string -departDate: string -purpose: string +display() : void +display(dest : string) : void

Pseudocode:

class Pay

Declarations

private string destination

private string meansOfTransport

private string departDate

private string purpose

public Trip()

destination = â€śXXXâ€ť

meansOfTransport = â€śXXXâ€ť

departDate = â€śXXXâ€ť

purpose = â€śXXXâ€ť

return

public Trip(string dest, string trans, string date,

string purp)

destination = dest

meansOfTransport = trans

departDate = date

purpose = purp

return

public void display()

output â€śDestination: â€ť, destination

output â€śMeans of Transportation: â€ť,

meansOfTransport

output â€śDeparture Date: â€ť, departDate

output â€śPurpose: â€ť, purpose

return

public void display(string dest)

if (destination = dest) then

output â€śDestination: â€ť, destination

output â€śMeans of Transportation: â€ť,

meansOfTransport

output â€śDeparture Date: â€ť, departDate

output â€śPurpose: â€ť, purpose

endif

return

endClass

b. Create an application that instantiates several Trip objects and demonstrates all the methods.

Pseudocode:

start

Declarations

Trip trip1

Trip trip2(â€śLondonâ€ť, â€śtrainâ€ť, â€ś6/14/2015â€ť,

â€śpleasureâ€ť)

Trip trip3(â€śParisâ€ť, â€śairâ€ť, â€ś12/16//2016â€ť,

trip1.display()

trip2.display()

trip3.display(â€śBostonâ€ť)

trip3.display(â€śParisâ€ť)

stop

6. Assigned

7. Assigned

a. Create a class for a cell phone service named Message that includes a field for the price of the message. Create get and set methods for the field.

Diagram:

 Message #price: num +setPrice(pr : num) : void +getPrice() : num

Pseudocode:

class Message

Declarations

protected num price

public void setPrice(num pr)

price = pr

return

public num getPrice()

return price

endClass

b. Derive three subclassesâ€”VoiceMessage, TextMessage, and PictureMessage. The VoiceMessage class includes a numeric field to hold the length of the message in minutes and a get and set method for the field. When a VoiceMessageâ€™s length value is set, the price is calculated at 4 cents per minute. The TextMessage class includes a numeric field to hold the length of the message in words and a get and set method for the field. When a TextMessageâ€™s length value is set, the price is calculated at 2 cents per word. The PictureMessage class includes a numeric field that holds the size of the picture in kilobytes and get and set methods for the field. When a PictureMessageâ€™s length value is set, the price is calculated at 1 cent per kilobyte.

Diagram (VoiceMessage):

 Message #price: num +setPrice(pr : num) : void +getPrice() : num

 VoiceMessage -length: num +setLength(len : num) : void +getLength() : num

Pseudocode (VoiceMessage):

class VoiceMessage inheritsFrom Message

Declarations

private num length

public void setLength(num len)

length = len

price = length * 4

return

public num getLength()

return length

endClass

Diagram (TextMessage):

 Message #price: num +setPrice(pr : num) : void +getPrice() : num

 TextMessage -length: num +setLength(len : num) : void +getLength() : num

Pseudocode (TextMessage):

class TextMessage inheritsFrom Message

Declarations

private num length

public void setLength(num len)

length = len

price = 2 * length

return

public num getLength()

return length

endClass

Diagram (PictureMessage):

 Message #price: num +setPrice(pr : num) : void +getPrice() : num

 PictureMessage -size: num +setSize(sz : num) : void +getSize() : num

Pseudocode (PictureMessage):

class PictureMessage inheritsFrom Message

Declarations

private num size

public void setSize(num sz)

size = sz

price = size

return

public num getSize()

return size

endClass

c. Design a program that instantiates one object of each of the three classes, and demonstrate using all the methods defined for each class.

Pseudocode:

start

Declarations

VoiceMessage vMessage

TextMessage tMessage

PictureMessage pMessage

vMessage.setLength(15)

tMessage.setLength(24)

pMessage.setSize(124)

output â€śVoiceMessage info:â€ť

output â€śLength = â€ť, vMessage.getLength()

output â€śPrice = â€ť, vMessage.getPrice()

output â€śTextMessage info:â€ť

output â€śLength = â€ť, tMessage.getLength()

output â€śPrice = â€ť, tMessage.getPrice()

output â€śPictureMessage info:â€ť

output â€śSize = â€ť, pMessage.getSize()

output â€śPrice = â€ť, pMessage.getPrice()

stop

a. Create a class named Order that performs order processing of a single item. The class has four fields: customer name, customer number, quantity ordered, and unit price. Include set and get methods for each field. The set methods prompt the user for values for each field. This class also needs a computePrice() method to compute the total price (quantity multiplied by unit price) and a method to display the field values.

Diagram:

 Order -customerName: string -customerNumber: num -quantityOrdered: num -unitPrice: num +setCustomerName() : void +setCustomerNumber() : void +setQuantityOrdered() : void +setUnitPrice() : void +getCustomerName() : string +getCustomerNumber() : num +getQuantityOrdered() : num +getUnitPrice() : num +computePrice() : num +displayValues() : void

Pseudocode:

class Order

Declarations

private string customerName

private num customerNumber

private num quantityOrdered

private num unitPrice

public void setCustomerName()

output â€śEnter a customer name:â€ť

input customerName

return

public void setCustomerNumber()

output â€śEnter a customer number:â€ť

input customerNumber

return

public void setQuantityOrdered()

output â€śEnter quantity ordered:â€ť

input quantityOrdered

return

public void setUnitPrice()

output â€śEnter a unit price:â€ť

input unitPrice

return

public string getCustomerName()

return customerName

public num getCustomerNumber()

return customerNumber

public num getQuantityOrdered()

return quantityOrdered

public num getUnitPrice()

return unitPrice

public num computePrice()

Declarations

num totalPrice

totalPrice = quantityOrdered * unitPrice

public displayValues()

output â€śCustomer name: â€ť, customerName

output â€śCustomer number: â€ť, customerNumber

output â€śQuantity ordered: â€ť, quantityOrdered

output â€śUnit price: â€ť, unitPrice

return

endClass

b. Create a subclass named ShippedOrder that overrides computePrice() by adding a shipping and handling charge of \$4.00.

Diagram:

 Order -customerName: string -customerNumber: num -quantityOrdered: num -unitPrice: num +setCustomerName() : void +setCustomerNumber() : void +setQuantityOrdered() : void +setUnitPrice() : void +getCustomerName() : string +getCustomerNumber() : num +getQuantityOrdered() : num +getUnitPrice() : num +computePrice() : num +displayValues() : void

 ShippedOrder +computePrice() : num

Pseudocode:

class ShippedOrder inheritsFrom Order

public num computePrice()

Declarations

num price

num SHIPPING_CHARGE = 4

price = getQuantityOrdered() * getUnitPrice() +

SHIPPING_CHARGE

return price

endClass

c. Create the logic for an application that instantiates an object of each of these two classes. Prompt the user for data for the Order object and display the results; then prompt the user for data for the ShippedOrder object and display the results.

Pseudocode:

start

Declarations

Order order1

ShippedOrder order2

order1.setCustomerName()

order1.setCustomerNumber()

order1.setQuantityOrdered()

order1.setUnitPrice()

order1.displayValues()

output â€śTotal Price: â€ť, order1.computePrice()

order2.setCustomerName()

order2.setCustomerNumber()

order2.setQuantityOrdered()

order2.setUnitPrice()

order2.displayValues()

output â€śTotal Price: â€ť, order2.computePrice()

stop

d. Create the logic for an application that continuously prompts for order information until the user enters ZZZ for the customer name or 10 orders have been taken, whichever comes first. Ask the user whether each order will be shipped, and create an Order or a ShippedOrder appropriately. Store each order in an array. When the user finishes entering data, display all the order information taken as well as the total price that was computed for each order.

Pseudocode:

start

Declarations

num x

num shippedCnt

num notShippedCnt

num MAX = 10

string QUIT = â€śZZZâ€ť

ShippedOrder shippedOrders[MAX]

Order notShippedOrders[MAX]

string name = â€śAAAâ€ť

string type

x = 0

shippedCnt = 0

notShippedCnt = 0

while x < MAX AND name <> QUIT

output â€śWill this order be shipped?â€ť

input type

if type = â€śyesâ€ť then

shippedOrders[shippedCnt].

setCustomerName()

shippedOrders[shippedCnt].

setCustomerNumber()

shippedOrders[shippedCnt].

setQuantityOrdered()

shippedOrders[shippedCnt].setUnitPrice()

name = shippedOrders[shippedCnt].

getCustomerName()

shippedCnt = shippedCnt + 1

else

notShippedOrders[notShippedCnt].

setCustomerName()

notShippedOrders[notShippedCnt].

setCustomerNumber()

notShippedOrders[notShippedCnt].

setQuantityOrdered()

notShippedOrders[notShippedCnt].

setUnitPrice()

name = notShippedOrders[notShippedCnt].

getCustomerName()

notShippedCnt = notShippedCnt + 1

endif

x = x + 1

endwhile

x = 0

while x < shippedCnt

shippedOrders[x].displayValues()

output â€śTotal Price: â€ť,

shippedOrders[x].computePrice()

x = x + 1

endwhile

x = 0

while x < notShippedCnt

notShippedOrders[x].displayValues()

output â€śTotal Price: â€ť,

notShippedOrders[x].computePrice()

x = x + 1

endwhile

stop

a. Design a method that calculates the cost of a weekly cleaning job for Mollyâ€™s Maid Service. Variables include a job location code of B for business, which costs \$200, or R for residential, which costs \$140. The method should throw an exception if the location code is invalid.

public num calculateCost(string location)

Declarations

num jobCost

num RESIDENTIAL_COST = 140

if location = "B" then

else

if location = "R" then

jobCost = RESIDENTIAL_COST

else

Exception mistake

throw mistake

endif

endif

return jobCost

b. Write a module that calls the module designed in Exercise 10a. If the module throws an exception, force the price of the job to 0.

public void getMaidData()

Declarations

string location

num cost

output â€śEnter the location >>â€ť

input location

try

cost = calculateCost(location)

endTry

catch(Exception mistake)

cost = 0

endCatch

output â€śThe cost is: â€ť, cost

return

c. Write a module that calls the module designed in Exercise 10a. If the module throws an exception, require the user to reenter the location code.

public void getMaidData()

Declarations

string location = â€śZâ€ť

num cost

while location = â€śZâ€ť

output â€śEnter the location >>â€ť

input location

try

cost = calculateCost(location)

endTry

catch(Exception mistake)

location = â€śZâ€ť

output â€śReenter locationâ€ť

endCatch

endwhile

output â€śThe cost is: â€ť, cost

return

d. Write a module that calls the module designed in Exercise 10a. If the module throws an exception, force the location code to â€śRâ€ť and the base price to \$140.

public void getMaidData()

Declarations

string location

num cost

output â€śEnter the location >>â€ť

input location

try

cost = calculateCost(location)

endTry

catch(Exception mistake)

location = â€śRâ€ť

cost = calculateCost(location)

endCatch

output â€śThe cost is: â€ť, cost

return

a. Design a method that calculates the monthly cost to rent a roadside billboard. Variables include the size of the billboard (S,M, or L, for small, medium, or large) and its location ( H, M, or L for high-, medium-, or low-traffic areas). The method should throw an exception if the size or location code is invalid. The monthly rental cost is shown in Table 11-1.

 High Traffic Medium Traffic Low Traffic Small size 100.00 65.00 35.00 Medium size 150.00 95.00 48.00 Large size 210.00 130.00 60.00

Table 11-1 Monthly billboard rental rates

public num calculateRent(string size, string location)

Declarations

num rent

num SMALL_HIGH = 100

num SMALL_MED = 65

num SMALL_LOW = 35

num MEDIUM_HIGH = 150

num MEDIUM_MED = 95

num MEDIUM_LOW = 48

num LARGE_HIGH = 210

num LARGE_MED = 130

num LARGE_LOW = 60

if size = "S" then

if location = â€śHâ€ť then

rent = SMALL_HIGH

else

if location = â€śMâ€ť then

rent = SMALL_MED

else

if location = â€śLâ€ť then

rent = SMALL_LOW

else

Exception mistake

throw mistake

endif

endif

endif

else

if size = "M" then

if location = â€śHâ€ť then

rent = MEDIUM_HIGH

else

if location = â€śMâ€ť then

rent = MEDIUM_MED

else

if location = â€śLâ€ť then

rent = MEDIUM_LOW

else

Exception mistake

throw mistake

endif

endif

endif

else

if size = â€śLâ€ť then

if location = â€śHâ€ť then

rent = LARGE_HIGH

else

if location = â€śMâ€ť then

rent = LARGE_MED

else

if location = â€śLâ€ť then

rent = LARGE_LOW

else

Exception mistake

throw mistake

endif

endif

endif

else

Exception mistake

throw mistake

endif

endif

endif

return rent

Performing Maintenance

1. A file named MAINTENANCE11-01.txt is included with your downloadable student files. Assume that this program is a working program in your organization and that it needs modifications as described in the comments (lines that begin with two slashes) at the beginning of the file. Your job is to alter the program to meet the new specifications.

// This program accepts product data about 100 products.

// It displays data about the most expensive product

// Modify the program to use a Product class to

// hold product data. Include a constructor

// that accepts all the data fields as parameters.

class Product

Declarations

private string idNum

private string description

private num price

public Product(string id, string descrip, num pr)

idNum = id

description = descrip

price = pr

return

public void setIdNum(string id)

idNum = id

return

public void setDescription(string des)

description = des

return

public void setPrice(num pr)

if pr < 0

price = 0

else

price = pr

endif

return

public string getIdNum()

return idNum

public string getDescription()

return description

public num getPrice()

return price

endClass

start

Declarations

num SIZE = 100

Product products[SIZE]

num x = 0

num total = 0

num avg

num highestPrice = 0

string highestId

string higestDescrip

while x < SIZE

products[x] = getData()

total = total + products[x].getPrice()

if products[x].getPrice() > highestPrice

highestPrice = products[x].getPrice()

highestDesc = products[x].getDescription()

highestId = products[x].getIdNum()

endif

x = x + 1

endwhile

avg = total / SIZE

output "The highest priced product is highestId,

highestDescrip, " \$", highestPrice

stop

Product getData()

string id

string descrip

num price

output "Enter id or "

input id

output "Enter description "

input descrip

output "Enter price "

input price

Product p(id, descrip, price)

return p

Find the Bugs

1. Your downloadable files for Chapter 11 include DEBUG11-01.txt, DEBUG11-02.txt, and DEBUG11-03.txt. Each file starts with some comments that describe the problem. Comments are lines that begin with two slashes (//). Following the comments, each file contains pseudocode that has one or more bugs you must find and correct.

DEBUG11-01

// This file defines the Patient class used by

// a doctor's office. The Patient class has two

// overloaded constructors -- a default constructor,

// and one that requires an ID number and full name.

// A demonstration program declares two Patient objects.

class Patient

Declarations

private string idNum

private string lastName

private string firstName

public Patient() // constructor should be public

idNum = "0000"

lastName = "XXXX"

firstName = "XXXX"

return

public Patient(string id, string last, string first)

idNum = id // field is idNum

lastName = last

firstName = first

return

public void display() // display() is a void method

output "Patient #", idNum, lastName, firstName

return

endClass

start

Declarations

Patient patient1

Patient patient2("234", "Lee", "Lydia")

patient1.display()

patient2.display()

stop

DEBUG 11-02

// This file defines the Building class

// and the Hotel class that inherits from it.

// A demonstration program declares and uses a Hotel object.

class Building

Declarations

private num squareFeet

public num getSquareFeet()

// getSquareFeet() is a num method

return squareFeet

public void setSquareFeet(num feet)

// setSquareFeet() requires a parameter

squareFeet = feet

return

return

endClass

class Hotel inheritsFrom Building

Declarations

private num numberOfRooms

public Hotel(string address, num sqFt, num rooms)

// must use set method to set address

setSquareFeet(sqFt)

// must use set method to set square feet

numberOfRooms = rooms

return

public num getNumberOfRooms

return numberOfRooms

endClass

start

Declarations

Hotel hotel("100 Main Street", 8000, 20)

hotel.getNumberOfRooms()

// must use object with each method call

stop

DEBUG11-03

// This program gets and displays the user's ID number

// which must be between 1000 and 8999 inclusive.

// If the ID is invalid, then an exception is thrown

// When the exception is caught, an error message is

// displayed and the ID is set to 0.

start

Declarations

num id

output "This program gets your ID"

try

id = getIdNum()

endtry

catch(Exception mistake)

output "Invalid ID number"

id = 0

// id should be set to a non-garbage value

endcatch

output "ID is ", id

// variable is id

stop

public num getIdNum()

Declarations

num idNum

num LOW = 1000

num HIGH = 8999

output "Please enter ID number "

input idNum

// variable is idNum

if idNum < LOW OR idNum > HIGH then

// test should be OR

Exception mistake

throw mistake

// throw the object mistake

endif

return idNum

// return the entered idNum

2. Your downloadable files for Chapter 11 include a file named DEBUG11-04.jpg that contains a class diagram with syntax and/or logical errors. Examine the class diagram and then find and correct all the bugs.

Game Zone

1. a. Computer games often contain different characters or creatures. For example, you might design a game in which alien beings possess specific characteristics such as color, number of eyes, or number of lives. Create an Alien class. Include at least three data members of your choice. Include a constructor that requires a value for each data field and a method named toString() that returns a string that contains a complete description of the Alien.

Diagram:

 Alien -color: string -numOfEyes: num -numOfLives: num +setColor(col : string) : void +setNumOfEyes(eyes : num) : void +setNumOfLives(lives : num) : void +getColor() : string +getNumOfEyes() : num +getNumOfLives() : num +toString() : void

Pseudocode:

class Alien

Declarations

private string color

private num numOfEyes

private num numOfLives

public Alien(string col, num eyes, num lives)

color = col

numOfEyes = eyes

numOfLives = lives

return

public void setColor(string col)

color = col

return

public void setNumOfEyes(num eyes)

numOfEyes = eyes

return

public void setNumOfLives(num lives)

numOfLives = lives

return

public string getColor()

return color

public num getNumOfEyes()

return numOfEyes

public num getNumOfLives()

return numOfLives

public void toString()

output â€śThe alien is â€ť, color, â€ś with â€ť,

numOfEyes, â€ś eyes and â€ť, numOfLives, â€ślivesâ€ť

return

endClass

b. Create two classesâ€”Martian and Jupiterianâ€”that descend from Alien. Supply each with a constructor that sets the Alien data fields with values you choose. For example, you can decide that a Martian object has four eyes but a Jupiterian object has only two.

Pseudocode (Martian):

class Martian inheritsFrom Alien

public Martian()

setColor(â€śgreenâ€ť)

setNumOfEyes(2)

setNumOfLives(1)

return

endClass

Pseudocode (Jupiterian):

class Jupiterian inheritsFrom Alien

public Jupiterian()

setColor(â€średâ€ť)

setNumOfEyes(5)

setNumOfLives(9)

return

endClass

c. Create an application that instantiates one Martian and one Jupiterian. Call the toString() method with each object and display the results.

Pseudocode:

start

Declarations

Martian marty

Jupiterian jupy

marty.toString()

jupy.toString()

stop

2. In Chapter 2, you learned that in many programming languages you can generate a random number between 1 and a limiting value named LIMIT by using a statement similar to randomNumber = random(LIMIT). In Chapters 4 and 5, you created and fine-tuned the logic for a guessing game in which the application generates a random number and the player tries to guess it. As written, the game should work as long as the player enters numeric guesses. However, if the player enters a letter or other non-numeric character, the game throws an automatically generated exception. Improve the game by handling any exception so that the user is informed of the error and allowed to attempt correct data entry again.

start

Declarations

num myRandomNumber

num guess = 0

num count

num LIMIT

string PROMPT = â€śEnter a number between 1 and â€ť

string CORRECT = â€śYou guessed correctly!â€ť

string HIGH = â€śYou guessed too high!â€ť

string LOW = â€śYou guessed too low!â€ť

myRandomNumber = random(LIMIT)

output PROMPT, LIMIT

count = 0

while guess <> myRandomNumber

try

guess = getGuess(LIMIT, PROMPT)

endtry

catch(Exception mistake)

guess = getGuess(LIMIT, PROMPT)

endcatch

count = count + 1

if guess = myRandomNumber then

output CORRECT

else

if guess > myRandomNumber then

print HIGH

else

print LOW

endif

endif

endwhile

output â€śIt took â€ť, count, â€ś guesses!â€ť

stop

public num getGuess(num limit, string prompt)

Declarations

num guess

output PROMPT, LIMIT

input guess

if guess not num then

Exception mistake

throw mistake

endif

return guess

3. a. In Chapter 10, you developed a Card class that contains a string data field to hold a suit and an integer data field for a value from 1 to 13. Now extend the class to create a class called BlackjackCard. In the game of Blackjack, each card has a point value as well as a face value. These two values match for cards with values of 2 through 10, and the point value is 10 for Jacks, Queens, and Kings (face values 11 through 13). For a simplified version of the game, assume that the value of the Ace is 11. (In the official version of Blackjack, the player chooses whether each Ace is worth 1 or 11 points.)

class BlackjackCard inheritsFrom Card

Declarations

private num pointValue

public void setPointValue()

{

Declarations

num value

num FACE_LIMIT = 11

num FACE_POINTS = 10

num ACE_POINTS = 11

value = getValue()

if value = 1 then

pointValue = ACE_POINTS

else

if value < FACE_LIMIT then

pointValue = value

else

pointValue = FACE_POINTS

endif

endif

}

public num getPointValue()

return pointValue

endClass

Declarations

private string suit

private num value

public void setSuit(num number)

{

string[] SUITS[4] = "diamonds", "clubs", "hearts", "spades"

suit = SUITS[number - 1];

}

public void setValue(num val)

value = val

return

public string getSuit()

return suit

public num getValue()

return value

endClass

start

Declarations

num SUIT_LIMIT = 4

num VALUE_LIMIT = 13

num suitNum

num value

Card card1

Card card2

suitNum = random(SUIT_LIMIT)

value = random(VALUE_LIMIT)

card1.setSuit(suitNum)

card1.setValue(value)

suitNum = random(SUIT_LIMIT)

value = random(VALUE_LIMIT)

card2.setSuit(suitNum)

card2.setValue(value)

output â€śCard 1 is: â€ť, card1.getValue(),

â€ś of â€ť, card1.getSuit()

output â€śCard 2 is: â€ť, card2.getValue(),

â€ś of â€ť, card2.getSuit()

stop

b. Randomly assign values to 10 BlackCard objects, then design an application that plays a modified version of Blackjack. In this version, the objective is to accumulate cards whose total value equals 21, or whose value is closer to 21 than the opponentâ€™s total value without exceeding 21. Deal five BlackjackCards each to the player and the computer. Make sure that each BlackjackCard is unique. For example, a deck cannot contain more than one Queen of Spades.

Determine the winner as follows:

Â· If the playerâ€™s first two, first three, first four, or all five cards have a total value of exactly 21, the player wins, even if the computer also achieves a total of 21.

Â· If the playerâ€™s first two cards do not total exactly 21, sum as many as needed to achieve the highest possible total that does not exceed 21. For example, suppose the playerâ€™s five cards are valued as follows: 10, 4, 5, 9, 2. In that case, the playerâ€™s total for the first three cards is 19; counting any more cards would cause the total to exceed 21.

Â· After you have determined the playerâ€™s total, sum the computerâ€™s cards in sequence. For example, suppose the computerâ€™s cards are 10, 10, 5, 6, 7. The first two cards total 20; you would not use the third card because it would cause the total to exceed 21.

Â· The winner has the highest total among the cards used. For example, if the playerâ€™s total using the first three cards is 19 and the computerâ€™s total using the first two cards is 20, the computer wins.

Display a message that indicates whether the game ended in a tie, the computer won, or the player won.

start

Declarations

num x = 0

num index

num suit

num faceValue

num playerSum

num playerWin

num playerDone

num computerWin

num computerDone

num computerSum

num SUIT_LIMIT = 4

num VALUE_LIMIT = 13

num NUM_OF_CARDS = 5

num TOTAL_CARDS = 52

num WINNING_NUMBER = 21

// set all array items to the value 1

num deckOfCards[TOTAL_CARDS] = 1

BlackjackCard playerCards[NUM_OF_CARDS]

BlackjackCard computerCards[NUM_OF_CARDS]

while x < NUM_OF_CARDS

playerCards[x].setValue(random(VALUE_LIMIT))

playerCards[x].setSuit(random(SUIT_LIMIT))

suit = playerCards[x].getSuit

faceValue = playerCards[x].getValue

// remove this card from the â€śdeckâ€ť

index = (suit+1) * faceValue

deckOfCards[index] = 0

computerCards[x].setValue(random(VALUE_LIMIT))

computerCards[x].setSuit(random(SUIT_LIMIT))

// if computer card is not in â€śdeckâ€ť

// get a new card, else remove card from â€śdeckâ€ť

suit = computerCards[x].getSuit

faceValue = computerCards[x].getValue

index = (suit+1) * faceValue

while deckOfCards[index] = 0 then

computerCards[x].setValue(random(VALUE_LIMIT))

computerCards[x].setSuit(random(SUIT_LIMIT))

endwhile

deckOfCards[index] = 0

x = x + 1

endwhile

// check values

x = 0

playerSum = 0

playerDone = 0

playerWin = 0

while x < NUM_OF_CARDS AND playerDone = 0

playerSum = playerCards[x] + playerSum

if playerSum = WINNING_NUMBER then

playerWin = 1

playerDone = 1

else

if playerSum > WINNING_NUMBER then

playerSum = playerSum â€“ playerCards[x]

playerDone = 1

endif

endif

x = x + 1

endwhile

// check values

x = 0

computerSum = 0

computerDone = 0

computerWin = 0

while x < NUM_OF_CARDS AND computerDone = 0 AND playerWin <> 1

computerSum = computerCards[x] + computerSum

if computerSum = WINNING_NUMBER then

computerWin = 1

computerDone = 1

else

if computerSum > WINNING_NUMBER then

computerSum = computerSum â€“ computerCards[x]

computerDone = 1

endif

endif

x = x + 1

endwhile

if playerWin = 1 OR playerSum > computerSum then

output â€śYou win!â€ť

else

if computerWin = 1 OR computerSum > playerSum then

output â€śThe computer wins!â€ť

endif

endif

stop

Up for Discussion

1. Many programmers think object-oriented programming is a superior approach to procedural programming. Others think it adds a level of complexity that is not needed in many scenarios. Find and summarize arguments on both sides. With which side do you agree?

Those who feel object-oriented programming is the superior approach cite its similarity to how objects operate in the real word. Data and its methods are packaged. Polymorphism provides more natural syntax and inheritance provides reusability. Those who feel procedural programming is the superior approach cite its simplicity. They feel object-orientation adds an unnecessary layer to what would otherwise be simple code.

2. Many object-oriented programmers are opposed to using multiple inheritance. Find out why and decide whether you agree with this stance.

Multiple inheritance has been criticized because of the increased complexity it causes, particularly in the chaining of constructors and destructors. Problems also arise if both base classes used for multiple inheritance have data members or methods with the same signature, leading to ambiguous situations. Many say that if you feel you need multiple inheritance, it is a sign of poor design.

3. If you are completing all the programming exercises in this book, you can see how much work goes into planning a full-blown professional program. How would you feel if someone copied your work without compensating you? Investigate the magnitude of software piracy in our society. What are the penalties for illegally copying software? Are there circumstances in which it is acceptable to copy a program? If a friend asked you to copy a program for him, would you? What should we do about this problem, if anything?