Homework 2: Coin Toss Simulation
- Review the dice simulation example files
Die.java and DieTest.java.
- In a file named
Coin.java, create a class named
Coin to simulate a coin which has two faces, heads and tails.
- The
Coin class should have two constants named
HEADS and TAILS, set to 0 and 1 (or true
and false).
- Each coin object should have a variable named
face
which is either HEADS or TAILS.
- Create a method to test the value of the coin face, e.g. one of these:
getFace() returns the value of face
isHeads() returns true if face is HEADS,
false if face is TAILS
- Implement a
flip() method to flip the coin. It should
randomly set face to either HEADS or
TAILS.
- e.g. If
Math.random() is greater than 0.5, set face to
HEADS, otherwise set face to TAILS.
- Create a constructor method
Coin(). When the coin is
initialized it should be flipped.
- In a file named
CoinTest.java, create a class named
CoinTest with just one method named main().
- Create a new
coin object.
- Ask the user to enter the number of coin flips
n.
- Loop to flip the coin
n times. Count and print how
many heads and how many tails occurred.
- Test and print whether the number of heads was greater than, less than or
equal to the number of tails.
- Check: Make sure all your variables, methods and classes are either
public or private as appropriate.
- Compile the programs by typing
javac Coin.java
CoinTest.java
- If there are no other Java files in the current directory you can simply
type
javac *.java.
- Run, test, debug and document the programs.
- Send the source code to the
instructor as two attachments in a message with subject java hw2.