Write a basic introductory program called that simulates a coin toss by generati
ID: 3529442 • Letter: W
Question
Write a basic introductory program called that simulates a coin toss by generating a random integer from the set {0, 1}, where 0 represents tails and 1 represents heads. Your program should prompt the user to enter the number of coin tosses that he/she would like to simulate. Then your program should simulate the number of coin tosses specified by the user, displaying the results of each toss to the screen. To implement the program, you are required to write and use some methods in your code; those methods are: getNumTossesExplanation / Answer
//I tried to use alot of documentation here,but comment if you if any question:
//CoinTosses.java
import java.util.Random;
import java.util.Scanner;
public class CoinTosses {
/**
* @param args
*/
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int NumTosses=getNumTosses(input); //get the number of tosses to simulate
simulateNTosses(NumTosses);
input.close();//close the Scanner
}
/**getNumTosses
* this method will prompt the user to enter the number of tosses that he/she would
* like to simulate and return this (integer) number
*
* precondition: user will enter a positive number
*
* @param input Scanner object for keyboard input
* @return NumTosses number of tosses to simulate
*/
public static int getNumTosses(Scanner input){
int NumTosses;
System.out.print("Enter number of coin tosses to simulate: ");
NumTosses=input.nextInt();
return NumTosses;
}
/**simulateNTosses
* this method will have one parameter for the number of tosses to be simulated
* and will perform the simulations.
* It should contain a for loop that iterates n times, where n is the number of
* coin tosses to be simulated.
*
* @param n the number of tosses to simulate
*/
public static void simulateNTosses(int n){
int result;
for(int i=1;i<=n;i++){//loop n times
result=simulateToss();//get result of toss
System.out.print("Toss # "+i+": ");
if(result==0)
System.out.println("tails");
else
System.out.println("heads");
}
return;
}
/**simulateToss
*
* @return result returns value fo either 0 or 1, produced by Random object
*/
public static int simulateToss(){
Random rand=new Random();//create rand of class Random
int result = rand.nextInt(2);//get a number between 0 and 1
return result;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.