Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipping a coin using RandomGenerator

Tags:

java

I'm trying to write a program that simulates flipping a coin. The first time the coin flips heads I want the program to exit. The first statement in my while loop flips the coin once. Then i have a if statement that says if the coin that I just flipped was heads exit the program. But my program is not working the way i want. Sometimes

My question is am I flipping the coin once or twice per 1 cycle in the while loop? Does the coin get flipped once in the while loop and then a second time in the if condition? I've tested it but it gives me a different result with different errors every time and I can't figure out why.

Is the if condition correct for what I'm trying to do in my program?

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

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


     while (true){
        println(flipCoin());
        if (flipCoin() == "heads"){
               break;
             }   
        }
  }

public String flipCoin(){
   String flip = rgen.nextBoolean() ? "heads" : "tails"; 
   return flip;
 }


public RandomGenerator rgen = RandomGenerator.getInstance();
}
like image 269
Jessica M. Avatar asked Jan 31 '26 21:01

Jessica M.


1 Answers

Every time you call flipCoin() the method runs, so it runs once on the line println(flipCoin()); and once on if (flipCoin() == "heads"). The results of the two calls may not be the same, you should store the result and then use the result, so:

    while (true){
        String result=flipCoin();
        System.out.println(result);
        if (result.equals("heads")){
            break;
        }   
    }

Note also that using == with strings will (under most circumstances) always give false; this is because == asks if they are literally the same object, not if their contents are equal (two pieces of paper can both have "hi" written on them but they are not the same piece of paper). .equals compares the contents of the two strings (i.e. if they say the same word(s)).

I have kept my modifications as close to your code as possible but you may want to consider the following possible improvements:

  • break; can have legitimate usages but usually is unnecessary, you could avoid it by:

    String result=flipCoin();
    while (result.equals("heads")==false){
        System.out.println(result);
        result=flipCoin();
    
    }
    
  • using strings as identifiers again has its place, but consider all the different capitalisations you could use (heads, Heads, HEADS), an enum may be a better choice.

like image 119
Richard Tingle Avatar answered Feb 03 '26 10:02

Richard Tingle



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!