Flipping a coin and stopping when it lands heads 4 times in a row

Viewed 56

The assignment is to flip a coin until four heads in a row are seen and display all the results leading up to that. I keep getting the last error message I put in just in case it fell through. I have no idea what I messed up and was wondering if someone was able to help.

class Main {
  public static void main(String[] args) {
  
      int h = 2;
      int t = 1;
  
      int count = 0;

      int result;

      while (count<=4)
      {
   
        result = (int)Math.random()*2;
        if (result == 2)
        {
        count++;
        System.out.print("H ");
        }
        else if (result == 1)
        {
        count=0;
        System.out.print("T ");
        }
        else
        System.out.println("error");
      }
  }
}
4 Answers
(int)Math.random() * 2

is the same as

((int)Math.random()) * 2

Given that Math.random() returns a number at least zero but less than one, your expression is always going to be zero.

Put in parentheses:

(int) (Math.random() * 2)

But then, also look at the values of result in your conditionals: you will never generate 2.

You need to add 1 to have possible values of one or two:

result = (int) (Math.random() * 2 + 1);

You can use the Randomclass and boolean

Random random = new Random();
int count = 0;
while (count < 4) {
    if (random.nextBoolean()) {
      System.out.print("H");
      count++;
    } else {
        count = 0;
        System.out.print("T");
    }
}

As the result of Math.random() is between 0 and 1 type casting it to int will remove the digits after decimal point and you'll always have zero as answer. Below code will help you to generate a random number between min and max.

// define the range 
      int max = 2; 
      int min = 1; 
      int range = max - min + 1; 
      int rand = (int)(Math.random() * range) + min;

For an explanation of how this works you can put the min possible value of 0 and max possible of 0.99 and multiply both by any range, let's say 20 the answer will still be in between 1 to 20.8 which gets turned to 20 as it's not rounding off but directly type casting. Hence, this can give you a random number for any range.

Related