jeudi 4 novembre 2021

Why is my code only getting all heads or all tails when using Math.random()?

I want to flip a coin and generate either heads or tails. heads = 0, tails = 1. It will then update an array where index 0 is the number of heads flipped and index 1 is the number of tails flipped. However, my code is either getting all heads or all tails. Is there a problem with the Math.random() number generator?

import java.util.Random;
import java.lang.Math;

class FlipCoin
{
    public static void main(String[] args)
    {
        int[] tracker = new int[2];
        int heads = 0;
        int tails = 1;
        int tosses = 10;

        coinFlip(tracker, heads, tails, tosses);

        //System.out.printf()
    }
    
    public static void coinFlip(int[] tracker, int heads, int tails, int tosses)
    {

        int flips =(int)(Math.random());
        
        for(int x = 0; x <= tosses; x++)
        {
            if (flips == heads) 
            {
                tracker[0] ++;
                System.out.println("You flipped heads!");
            } 
            else if (flips == tails)
            {
                tracker[1] ++;
                System.out.println("You flipped tails!");
            }
        }

        for(int i = 0; i < tracker.length; i++)
        {
            System.out.println(tracker[i] + " ");
        }

    }
}



Aucun commentaire:

Enregistrer un commentaire