In: Computer Science
(java) Write a class called CoinFlip. The class should have two instance variables: an int named coin and an object of the class Random called r. Coin will have a value of 0 or 1 (corresponding to heads or tails respectively). The constructor should take a single parameter, an int that indicates whether the coin is currently heads (0) or tails (1). There is no need to error check the input. The constructor should initialize the coin instance variable to whatever was passed in as the parameter, it should also inistantiate r to be a new instance of the Random class. In addition to the constructor there should be a mutator method called flip which takes no parameters and randomly assigns the value of coin to either 0 or 1. There should be an accessor method that returns the current value of coin as an int.
Then write a code fragment that instantiates a CoinFlip object that is initially set to heads. Using the methods from above, flip the coin twice and print out the result each time.
coin.java
import java.io.*;
import java.util.*;
class coinFlip
{
//member varaibles
private int coin;
private Random r;
//parameterized constructor
public coinFlip(int n)
{
coin = n; //set coin value
r = new Random(); //initiate Random
class object to new instance
}
//mutator method
public void flip()
{
coin = r.nextInt(2); //set random
value in between 0 and 1
}
//accessor method
public int coinValue()
{
return coin; //return coin
value
}
}
public class coin
{
public static void main(String args[]) throws Exception
{
coinFlip obj = new coinFlip(1); //create new instance
of class coinFlip
System.out.println(obj.coinValue()); //print coin value (head = 0 ,
tails = 1 )
obj.flip(); //flip coin with mutator
method
System.out.println(obj.coinValue()); //print coin
value again
}
}
OUTPUT