class - Java Program (Coin Flip simulation) -
this code fliprace program initiates race between 2 coins. goal globally declared variable. whichever coin reaches goal number of heads fastest wins. below code coin class.
my problem if put goal = 3 , whichever coin gets 3 heads fastest wins, works ok. when set goal = 4 , still works ok. weird starts happening once put goal > 4. put goal = 7, still final result comes when 1 coin has registered 4 heads not 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 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; } }
Comments
Post a Comment