Answers for "repeated coin flip program in java"

0

repeated coin flip program in java

/*

This program is a coin flipper program. It flips a coin and generates a String
of results based on what it flipped.

This program uses BigInteger. Used BufferedReader with BigInteger.

*/

import java.io.*;
import java.math.BigInteger;

public class Main
{
	public static void main(String[] args) throws IOException {
	   
	    BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
	    
	    BigInteger counter=BigInteger.ZERO;//set to this value for use in loop
	    BigInteger num_of_flips=BigInteger.ZERO;//dummy value
	    
	    BigInteger num_heads=BigInteger.ZERO;//for tracking purposes
	    BigInteger num_tails=BigInteger.ZERO;//for tracking purposes
	    
	    
	    //int num_of_flips;
	    int flip;
	    //int num_head=0;
	    //int num_tail=0;
	    boolean track_data=true;//If set to false then we will not track the number of heads/tails
	    
		System.out.println("Please input the number of coin flips to do.");
		num_of_flips=new BigInteger(br.readLine());
		
		while(counter.compareTo(num_of_flips)<0){
		    flip = CoinFlip();
		    System.out.print(flip);
		    
		    
		    if (track_data==true){
		        if (flip==1){
		            num_heads=num_heads.add(BigInteger.ONE);
		        }
		        else{
		            num_tails=num_tails.add(BigInteger.ONE);
		        }
		    }
		    
		    counter=counter.add(BigInteger.ONE);
		}
		
		if (track_data==true){
    		System.out.println();
    		System.out.println("Heads appeared "+num_heads+" times.");
    		System.out.println("Tails appeared "+num_tails+" times.");
		}
		
	}
	
	public static int CoinFlip(){
	    int i;
	    i = (int)(2*Math.random());
		return i;
	}
	
}
Posted by: Guest on January-15-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language