Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipping three consecutive heads then program exits using RandomGenerator

Tags:

java

random

I'm stuck on a problem that I don't know how to solve. I'm trying to use the RandomGenerator to simulate flipping a coin until the RandomGenerator flips 3 consecutive heads then at which point the program exits.

Variable flipCounter tracks the total number of flips and variable headsFlip tracks the consecutive heads that are flipped. The if condition says if the flip was heads start the headsFlips counter up to 3 but if the next flip is tails headsFlips resets to zero.

When i run the program it just prints the last statement in my run method and does not even run the while loop. I don't know why the program isn't working as I expect it to work.

import acm.program.*;
import acm.util.*;

public class HeadsFlipThreeInARow extends ConsoleProgram{
public void run(){

 int flipCounter = 0; 
 int headsFlip = 0; 

 while (headsFlip == 3){

 String flip = coinFlip();
 println(flip);

  if (flip.equals("heads")){
    headsFlip += 1;
  }else{
    headsFlip = 0;
  }

 flipCounter++;
 flip = coinFlip();
 } /* end of while loop  */
 println("It took " + flipCounter + "flips to reach 3 consecutive heads.");
 } /* end of run method */


private String coinFlip (){
String flip = rgen.nextBoolean() ? "heads" : "tails";
return flip; 

}

private RandomGenerator rgen = RandomGenerator.getInstance();

}
like image 879
Jessica M. Avatar asked Dec 14 '25 23:12

Jessica M.


1 Answers

while (headsFlip == 3){

shouldn't this be

while (headsFlip < 3){
like image 159
dfb Avatar answered Dec 16 '25 11:12

dfb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!