Problems Generating A Math.random Number, Either 0 or 1

You could use boolean values of 0 or 1 based on value of Math.random() as a double between 0.0 and 1.0 and make the random generator much simpler. And you can get rid completely of the coinToss() method.

if(Math.random() < 0.5) {
    answer = "Tails";

Remove the coin toss method and replace the first conditional with the code above.

Math.random(); by itself will return a value between 0.0 and less than 1.0. If the value is in the lower half, [0.0, 0.5), then it has the same probability of being in the upper half, [0.5, 1.0). Therefore you can set any value in the lower half as true and upper as false.

Leave a Comment