A Problem Solved: Representing Coins
In this lesson, we solve a problem using enumeration.
We'll cover the following...
Problem statement
Imagine that we need to represent coins in various programs. A coin has two sides, heads and tails. Additionally, a coin has a monetary value and shows the year in which it was minted. Let’s decide that these characteristics are sufficient for our purposes and create a class of coins.
Designing the class
We’ll name the class Coin
and give it four data fields, as follows:
sideUp
—a designation for heads or tailsname
—the coin’s name as a stringvalue
—a representation of the coin’s valueyear
—a positive integer denoting the year the coin was minted
Let’s also give the class the following methods:
- Accessor methods that return the coin’s visible side—heads or tails—its name, its value in cents, and its mint year
- Boolean-valued methods that test whether the coin’s visible side is heads or tails
- A method that simulates a coin toss by assigning a designation for heads or tails to
sideUp
at random - The method
toString
Access this course and 1400+ top-rated courses and projects.