无法弄清楚如何检测硬币夹中有多少个连续的磁头

时间:2019-03-09 22:32:09

标签: java random while-loop

我在java类中有一个正在处理的项目,无法弄清楚几行代码。

该项目包括掷硬币,并使用各种方法来检测到目前为止有多少头或尾以及发生了多少次翻转。

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);
}    

}

我似乎无法解决的问题是在另一个名为TossingCoins的类中,并且是方法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);
}
}

到目前为止,我一直在尝试查看numHeads是否不等于heads的目标。然后,如果它不等于正面(目标)的数量,我将翻转设置为加一个。直到第一个击球次数达到1、2、3、4、5,依此类推,直到击中击球次数(目标)。

0 个答案:

没有答案