例如,我有一个编程任务,要求我制作一个硬币类和一个随机翻转硬币40次的驱动程序类,然后计算最终结束头尾的次数。好吧,到目前为止我得到了整个代码:
public class driver {
public static void main(String[] args) {
coin myCoin = new coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
}
}
}
public class coin {
protected String sideUp;
public coin() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public void toss() {
if (Math.random() < 0.5)
this.sideUp = "heads";
else
this.sideUp = "tails";
}
public String getSideUp() {
return this.sideUp;
}
}
这一切都已完成,但我如何计算每个头部或尾部的实例?
答案 0 :(得分:2)
在进行投掷时计算它们而不是结束。如果赋值禁止此操作,请将结果保存到数组中,并在结尾处对数组中的结果进行计数。
答案 1 :(得分:0)
每次折腾后,只需检查一下您的硬币是头还是尾。
你可以将每个状态(头部/尾部)的计数器保存在如下数组中:
Coin myCoin = new Coin();
System.out.println("Coin initially is " + myCoin.getSideUp());
int[] coinCount = new int[2];
for (int i = 0; i < 40; i++) {
myCoin.toss();
System.out.println("Coin is now " + myCoin.getSideUp());
if(myCoin.getSideUp().equals("heads")){
coinCount[0]++;
} else {
coinCount[1]++;
}
}
System.out.println("Heads: "+coinCount[0]);
System.out.println("Tails: "+coinCount[1]);