这是FlipRace程序的代码,它启动两个硬币之间的竞赛。 GOAL是全局声明的变量。无论哪个硬币达到目标头数最快的胜利。下面是Coin类的代码。
我的问题是,如果我把GOAL = 3,那么哪个硬币获得3个最快的胜利,它就可以了。当我设置GOAL = 4时,仍然可以正常工作。但是一旦我把GOAL> 4.假设我把GOAL = 7,最后的结果仍然只有当一枚硬币已注册4个头而不是7时。
// FlipRace.java
package nisarg;
public class FlipRace {
public static void main(String[] args){
final int GOAL = 6;
int count1=0,count2=0;
Coin myCoin1 = new Coin();
Coin myCoin2 = new Coin();
while(count1 < GOAL && count2 < GOAL){
myCoin1.Flip();
myCoin2.Flip();
System.out.print("Coin1 : " +myCoin1 +"\t");
System.out.println("Coin2 :"+myCoin2);
count1 = (myCoin1.isHeads())? count1+1 : 0;
count2 = (myCoin2.isHeads())? count2+1 : 0;
}
if(count2 < GOAL) {
System.out.println("Coin1 wins!!");
} else if(count1 < GOAL){
System.out.println("Coin2 wins!!");
}
else {
System.out.println("Its a tie!!");
}
}
}
// Coin.java
package nisarg;
import java.util.Random;
public class Coin {
private final int HEADS = 1;
private final int TAILS = 0;
private int face;
public Coin(){
Flip();
}
public void Flip(){
face = (int)(Math.random()*2);
}
public boolean isHeads(){
return(face == HEADS);
}
public String toString(){
String faceName;
if(face == HEADS){
faceName = "H";
}
else {
faceName = "T";
}
return faceName;
}
}