Coding Exercises: Classes and Objects
Person
Write a Person class that includes the
following:
- member variables for name and number of pets
- constructor taking name and number of pets as input
- member function
greeting()that returns a string: “Hello, my name is (name) and I have (numberOfPets) pets.”
Write some test code that instantiates some Person
objects and demonstrates that the functions are working
properly.
ScoreKeeper
Write a ScoreKeeper class that includes the
following:
- member variable to keep track of the score (initialized to 0)
- method
scoreNormal()that adds 100 to the score - method
scoreBonus()that adds 1000 to the score
Write some test code that instantiates a ScoreKeeper
object and tests its functions.
Magic Eight Ball
Write a MagicEightBall class that includes the
following:
- a list of strings representing the possible replies
- member function
ask()that takes a single string as input, ignores it, and returns a string randomly from the possible replies
Write some code that instantiates a MagicEightBall
object and asks it some important questions.
Rectangle
Write a Rectangle class that includes the
following:
- member variables for base and height
- constructor with base and height as inputs
- member function to return the area of the rectangle
- member function to return the perimeter of the rectangle
- member function to return the length of a diagonal of the rectangle
Write test code to demonstrate that your Rectangle class functions all work properly.
Bonus Challenge: Vector
Write a Vector class that represents a
two-dimensional vector \(\vec{v} =
\left<x, y\right>\).
Include the following:
- member variables for \(x\) and \(y\)
- constructor taking \(x\) and \(y\) as input
- member function that returns the magnitude of the vector
- member function that returns the direction of the vector (Note:
this is a little tricky in general because you need to use atan()
and check the quadrant. Fortunately, the
mathlibrary includes a convenient functionatan2(y, x)that does this check for you. Note thatycomes beforex.) - member function that adds another vector to this one (like
+=):add(u) - member function that multiplies this vector by a scalar (like
*=):scalarMultiply(k) - member function that computes and returns the dot product of
this vector with another vector:
dotProduct(u) - member function that calculates the angle between this and
another vector:
angle(u)Hint: Use what you know from pre-calculus, together withmath.acos()and thedotProductandmagnitudefunctions above.
Be sure to write code to verify that your functions are all doing what they’re supposed to be doing.