For this assignment, you will design, implement, and experiment with a class that models a weighted coin.
The constructor for your WeightedCoin
class should have an integer parameter
specifying the likelihood of obtaining HEADS from a random flip. For example, suppose you entered 50
at the BlueJ prompt when creating a WeightedCoin
object.
That coin would then have a 50% chance of producing HEADS on any given flip. If you specified 90,
however, then each flip would have a 90% chance of being HEADS.
Your class should have the following methods.
String flip()
WeightedCoin
object constructed with input
75 should have a 75% chance of returning "HEADS".
int getNumberOfFlips
double getPercentageOfHeads
You should consider having a a Die
object as a field of your class, as a 100-sided die would be
extremely useful in determining the outcome of a flip. Since there is no reason to have more than
one 100-sided die, you can make this field static
so that it is shared by all
WeightedCoin
objects.
As before, your code should demonstrate good style. The class should have a comment block that describes
its purpose, as well as your name (under @author
) and date (under @version
).
Similarly, each method should have comment
block that describe its behavior as well as any parameters (under @param
) and return
values (under @return
).
Statements should be consistently indented to highlight structure, and all
method/variable names should be meaningful.
Testing your class to ensure that it behaves correctly can be a tedious
task. For example, suppose you created a WeightedCoin
object with a 60% likelihood of
producing HEADS on a given flip. If you flipped that coin 10 times, you wouldn't necessarily
obtain 6 out of 10 HEADS. Instead, you might get 5, or 7, or even something farther off.
When the number of flips is small, a few extra lucky HEADS (or unlucky TAILS) can greatly skew the
statistics. It is only when the number of repetitions is large that these lucky/unlucky stretches
balance out and you get consistent results. More formally, the Law of Large Numbers
states that the percentage of HEADS will approach the expected value as the number of repetitions
approaches infinity.
Add the following method to your WeightedCoin
class:
Use this method to verify the behavior described by the Law of
Large Numbers. In particular, create three different coins, each with a different likelihood
of obtaining HEADS (50%, 75%, and 90%). Then, make calls to the repeatedFlips
method
and report the percentage of HEADS for each coin after 10, 100, 1,000, and 10,000 flips. Do the
percentages appear to be converging on the expected values?
likelihood of HEADS | % after 10 flips | % after 100 flips | % after 1,000 flips | % after 10,000 flips |
---|---|---|---|---|
50% | ||||
75% | ||||
90% |