I have a project I am working on in my java class and cannot figure out what a few lines of code.
The project consists of flipping a coin and using various methods to detect how many heads or tails as well as how many flips have occurred so far.
import java.util.*;
public class GVcoin{
// true for heads, false for tails
private boolean isHeads;
private int flips, heads;
private Random r;
//Create the coin
public GVcoin(){
r = new Random();
heads = 0;
flips = 0;
isHeads = true;
}
//Flip the coin by random choosing true / false
public void flip(){
isHeads = r.nextBoolean();
flips++;
if(isHeads){
heads++;
}
}
//return true if coin is currently heads
public boolean isHeads(){
return isHeads;
}
//return String representation of important values
public String toString(){
String str;
str = "Flips: " + flips + " Heads: " + heads + " isHeads: " + isHeads;
return str;
}
//return number of total flips
public int numFlips(){
return flips;
}
//return number of total heads
public int numHeads(){
return heads;
}
//return number of total tails
public int numTails(){
return flips - heads;
}
//Set the coin to heads (or tails) to start
public void setToHeads(boolean h){
isHeads = h;
}
//Create the coin with a random seed
public GVcoin(int seed){
this();
r = new Random(seed);
}
}
The problem I can not seem to figure out is in a different class called TossingCoins and is the method public int consecutiveHeads(GVcoin c, int goal)
public class TossingCoins {
public int countHeads(GVcoin c, int goal){
while(c.numHeads() != goal) {
c.flip();
}
return c.numFlips();
}
public int flipForTails(GVcoin c, int goal){
while(c.numTails() != goal) {
c.flip();
}
return c.numFlips();
}
public int consecutiveHeads(GVcoin c, int goal){
while(c.numHeads() != goal){
c.flip();
}
}
// This method creates a TossingCoins object and calls the method for testing
public static void main(String[] args) {
TossingCoins game = new TossingCoins();
GVcoin c = new GVcoin();
int numHeads = game.countHeads(c, 100);
}
}
What I have tried so far is see if the numHeads is not equal to the goal of heads. Then if it is not equal to the number of heads(goal), I would set the flip to add one. Which wold count 1, 2, 3, 4, 5 and so on till it hits the amount flips needed to hit the number of heads(goal).
Aucun commentaire:
Enregistrer un commentaire