How flipping a coin and display tails and heads counting?

Fred882401 picture Fred882401 · Apr 11, 2014 · Viewed 16.5k times · Source

I am very beginner on Java, still getting passion about. I have been given this exercise: "Write a simulator program that flips a coin: One thousand times then prints out how many time you get tails and how many times you get heads" That is what i have tried to do so far.

import java.util.Random; 
import java.util.regex.Pattern; 

public class coin { 

    public static void main( String [] args ) { 

        Random r = new Random(); 
        Pattern tail = Pattern.compile("Tail+"); 
        Pattern head = Pattern.compile("Head+"); 
        String flips = ""; 

        for (int i = 0; i < 1000; i++) { 
            flips += r.nextInt(100) % 2 == 0 ? "Head" : "Tail"; 
        } 
        String[] heads = head.split( flips ); 
        String[] tails = tail.split( flips ); 
        //Display
        System.out.println("Times head was flipped:" + heads.length); 
        System.out.println("Times tail was flipped:" + tails.length); 
    }
}

The program seems to be working, but it is giving me always an almost pair amount of heads and tails, which the total exceed 1000, at least by 1 or more. Please, someone has any solution of this? Where am I wrong? Thanks

Answer

Kakarot picture Kakarot · Apr 11, 2014

Rather than appending the result in a String and then splitting the string and counting the occurence of "Head"/"Tail" you can just keep track of the count in separate variables :

int headCount = 0;
int tailCount = 0;

for (int i = 0; i < 1000; i++) {
    if(r.nextInt(100) %2 == 0)
    {
      headCount++;
    }
    else
    {
      tailCount ++;
    }

  System.out.println("Times head was flipped:" + headsCount); 
  System.out.println("Times tail was flipped:" + tailCount); 

}