I figured out how to make a coin class. But i can't figure out how to write a program to find the length of the longest run of heads in 100 flips of the coin.
This is what i did so far the runs program. Thanks
// this is the coin class
import java.util.Random;
public class Coin
{
private int face;
private final int HEADS=0;
private final int TAILS=1;
public Coin()
{
flip();
}
public void flip()
{
Random gen=new Random();
face=gen.nextInt(2);
}
public boolean isHeads()
{
return(face==HEADS);
}
public int getFace ()
{
return face;
}
public String toString()
{
String facename;
if(face==TAILS)
facename="Tails";
else
facename="Heads";
return facename;
}
}
//************************************************** ******************
// Runs.java
//
// Finds the length of the longest run of heads in 100 flips of a coin.
// ************************************************** ******************
public class Runs
{
public static void main (String[] args)
{
final int FLIPS = 100; // number of coin flips
int currentRun = 0; // length of the current run of HEADS
int maxRun = 0; // length of the maximum run so far
// Create a coin object
Coin myCoin = new Coin();
//this is the part i don't know how to do but tried something
// Flip the coin FLIPS times
for (int i = 0; i < FLIPS; i++)
{
// Flip the coin & print the result
myCoin.flip();
System.out.println(myCoin);
// Update the run information
if (myCoin.getFace() == 0)
{
currentRun = currentRun + 1;
}
else
{
if (currentRun > maxRun)
maxRun = currentRun;
currentRun = 0;
}
}
// Print the results
System.out.println("The longest run of heads is: " + maxRun);
}
}