Securing Higher Grades Costing Your Pocket? Book Your Coursework Help at The Lowest Price Now!

• +1-617-874-1011 (US)
• +44-117-230-1145 (UK)

# Programming Logic and Design Sample Assignment

14 Download     📄   20 Pages / 4765 Words

Programming Exercises

1. Complete the following tasks:

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.

Answer: A sample solution follows

Diagram:

 Circle -radius: num -area: num -diameter: num +setRadius(rad : num) : void +getRadius() : num +getArea() : num +getDiameter() : num

Pseudocode:

class Circle

Declarations

private num radius

private num area

private num diameter

public Circle()

radius = 1

return

public void setRadius(num rad)

if rad <= 0 then

radius = 1

else

radius = rad

endif

diameter = 2 * radius

area = (radius * radius) * 3.14

return

public num getRadius()

return radius

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.

Answer: A sample solution follows

Pseudocode:

start

Declarations

Circle myCircle

Circle yourCircle

myCircle.setRadius(5)

output “Circle 1 info:”

output myCircle.getRadius()

output myCircle.getArea()

output myCircle.getDiameter()

output “Circle 2 info:”

output yourCircle.getRadius()

output yourCircle.getArea()

output yourCircle.getDiameter()

stop

2. Complete the following tasks:

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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

4. Complete the following tasks:

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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

5. Complete the following tasks:

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

Pseudocode:

start

Declarations

Trip trip1

Trip trip2(“London”, “train”, “6/14/2015”,

“pleasure”)

Trip trip3(“Paris”, “air”, “12/16//2016”,

“business”)

trip1.display()

trip2.display()

trip3.display(“Boston”)

trip3.display(“Paris”)

stop

6. Assigned

7. Assigned

8. Complete the following tasks:

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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

9. Complete the following tasks:

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.

Answer: A sample solution follows

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

return totalPrice

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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

10. Complete the following tasks:

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.

Answer:

public num calculateCost(string location)

Declarations

num jobCost

num BUSINESS_COST = 200

num RESIDENTIAL_COST = 140

if location = "B" then

jobCost = BUSINESS_COST

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.

Answer:

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.

Answer:

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.

Answer:

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

11. Complete the following tasks:

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

Answer:

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.

Answer :

// This program accepts product data about 100 products.

// It displays data about the most expensive product

// and the average price of all products.

// 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

output "The average price of all products is \$", avg

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.

Answer :

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 string streetAddress

private num squareFeet

public string getAddress()

return streetAddress

public num getSquareFeet()

// getSquareFeet() is a num method

return squareFeet

public void setSquareFeet(num feet)

// setSquareFeet() requires a parameter

squareFeet = feet

return

public void setStreetAddress(string address)

streetAddress = address // assign parameter to field

return

endClass

class Hotel inheritsFrom Building

Declarations

private num numberOfRooms

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

setStreetAddress(address)

// 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)

output hotel.getAddress(), hotel.getSquareFeet(),

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.

Answer :

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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.

Answer: A sample solution follows

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.

Answer:

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.)

Answer: A sample solution follows

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.

Answer: A sample solution follows

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?

Answer :

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.

Answer :

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?

Answer :

Different sources report different dollar amounts, but software piracy seems to account for at least \$13 billion in software revenue lost worldwide per year.

According to the U.S. Copyright Act, illegal reproduction of software is subject to civil damages of as much as \$100,000 per title infringed plus criminal penalties, including fines of as much as \$250,000 per title infringed and imprisonment of up to five years.

Companies devote a large portion of their earnings to the creation of new software products. The programmers, writers, and all those involved in the creation of these new products deserve fair compensation. Companies will not continue to develop new products unless they can make a profit. Just as every customer pays a little for a store’s losses to shoplifters, every purchaser of legal software pays a little for illegal copies.

Students may agree with some of this, but have a hard time denying a friend a copy of a program. They might argue that, “The software companies can afford it and I am just a poor student,” and “It only costs a few cents for a blank CD. Why should I pay \$100 for one?”

## Cite This work.

To export a reference to this article please select a referencing stye below.

Urgent Homework (2022) . Retrive from https://www.urgenthomework.com/sample-homework/programming-logic-and-design-sample-assignment

"." Urgent Homework ,2022, https://www.urgenthomework.com/sample-homework/programming-logic-and-design-sample-assignment

Urgent Homework (2022) . Available from: https://www.urgenthomework.com/sample-homework/programming-logic-and-design-sample-assignment

[Accessed 09/12/2022].

Urgent Homework . ''(Urgent Homework ,2022) https://www.urgenthomework.com/sample-homework/programming-logic-and-design-sample-assignment accessed 09/12/2022.

## Buy Programming Logic and Design Answers Online

Talk to our expert to get the help with Programming Logic and Design to complete your assessment on time and boost your grades now

The main aim/motive of the management assignment help services is to get connect with a greater number of students, and effectively help, and support them in getting completing their assignments the students also get find this a wonderful opportunity where they could effectively learn more about their topics, as the experts also have the best team members with them in which all the members effectively support each other to get complete their diploma assignments. They complete the assessments of the students in an appropriate manner and deliver them back to the students before the due date of the assignment so that the students could timely submit this, and can score higher marks.Â The experts of the assignment help services at urgenthomework.com are so much skilled, capable, talented, and experienced in their field of programming homework help writing assignments, so, for this, they can effectively write the best economics assignment help services.

### Get Online Support for Programming Logic and Design Assignment Help Online

#### Resources

• 24 x 7 Availability.
• Trained and Certified Experts.
• Deadline Guaranteed.
• Plagiarism Free.
• Privacy Guaranteed.
• Free download.
• Online help for all project.
• Homework Help Services

#### Testimonials

Urgenthomework helped me with finance homework problems and taught math portion of my course as well. Initially, I used a tutor that taught me math course I felt that as if I was not getting the help I needed. With the help of Urgenthomework, I got precisely where I was weak: Sheryl. Read More