...

/

A Problem Solved: Representing Coins

A Problem Solved: Representing Coins

In this lesson, we solve a problem using enumeration.

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 tails
  • name—the coin’s name as a string
  • value—a representation of the coin’s value
  • year—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.