vendredi 14 août 2015

Exercise on heads or tails: Random class

I made a very simple random generator on heads or tails.
When playing 100 times, the result always fluctuates around a relation of 60/40 at max. In other words: I never get a result of let's say 35 - 65, or even 25 - 75.
What I find a bit remarkable is that I relatively often get a result of 50/50.
What is the reason for this?

Here is my main class (method named "play"):

package headsOrTails;

public class App {

    public static void main(String[] args) { 
        HeadsOrTails headsOrTails = new HeadsOrTails(100); 
        headsOrTails.play(); 

        System.out.println(headsOrTails.getTotalHeads()); 
        System.out.println(headsOrTails.getTotalTails()); 
    } 

}

My HeadsOrTails class where the random number gets generated:

package headsOrTails;

import java.util.Random;

public class HeadsOrTails {

    private int nrOfThrows; 
    private int totalTails; //0 
    private int totalHeads;  //1 

    //Constructor 
    public HeadsOrTails(int nrOfThrows){ 
        this.nrOfThrows = nrOfThrows; 
    } 

    public int getTotalTails(){
        return this.totalTails; 
    } 

    public int getTotalHeads(){ 
        return this.totalHeads; 
    } 

    public void play(){ 
        for (int i = 0; i < this.nrOfThrows; i++) {
            Random random = new Random(); 
            int rnd = random.nextInt(2); 

            if(rnd == 0){ 
                this.totalTails++; 
            } else { 
                this.totalHeads++; 
            }
        }

    } 
} 




Aucun commentaire:

Enregistrer un commentaire