A Biased Coin
- Create a new class named BiasedCoin that models a biased coin (heads
and tails are not equally likely outcomes of a flip). To do this you will modify the
Coin class from the text (in the file Coin.java).
To do this in BlueJ, add the Coin.java class to your project as usual. Open the file, then change "class Coin" to "class BiasedCoin" and save the file. This will create a new file, BiasedCoin.java, in your project directory/folder. Okay, now, you should alter the BiasedCoin class as
follows:
- You need to ensure that your constructor has the same name as the
class (i.e., BiasedCoin).
- Add a private data member bias of type double. This data member
will be a number between 0 and 1 (inclusive) that represents the probability
the coin will be HEADS when flipped. So, if bias is 0.5, the coin is an
ordinary fair coin. If bias is 0.6, the coin has probability 0.6 of coming
up heads (on average, it comes up heads 60% of the time).
- Modify the default constructor by assigning the value 0.5 to bias. This will make the default coin a fair one.
- Modify flip so that it generates a random number then assigns
face a value of HEADS if the number is less than the bias; otherwise
it assigns a value of TAILS. You may want to review Java's Random class.
- Add a second constructor with a single parameter that is a double-- that parameter
will be the bias. If the parameter is valid (a number between 0 and 1
inclusive) the constructor should assign the bias data member the
value of the parameter; otherwise it should assign bias a value
of 0.5. Call flip (as the other constructor does) to initialize the value
of face.
- Create a modified version of the Runs
program from the last exercise (call it BiasedRuns) that uses the
BiasedCoin class. The program should prompt the user to provide an initial bias toward heads. If the user enters a value less than 0 set the bias to 0, if it is greater than 1, set the bias to 1.
- The hardcopy you hand in should show two executions of BiasedRuns, using different biases.