In: Computer Science
You have just been put in charge of safety at your plant. The probability of an injury occuring on any given day is p. Your boss says that once the company has 10 totoal days in which at least one injury is reported the insurance premium triples. To plan financially, she wants to know how many days to expect until the insurance premium is going to triple. Write a class called SafetyAnalysis.java that does the following:
a. Reads in a value of p from the user. Checks if it is a double and a feasible probability.
b. Determines if there is an injury each day. To do this, generate a random number between 0 and 1. If the number you generated is less than p then there was an injury. Otherwise, there was not an injury on that day.
c. Continue determining if there was an injury each day until a total of 10 days worth of injuries have occurred (hint: use a loop where you don’t know how many iterations are required).
d. Repeat b. - c. 1000 times (hint: use a loop where you do know how many iterations are required). Return the average number of days it takes until 10 total injuries occur. (hint: each time you complete c., you have a new value to include in your average) e. Report the average number of days over the 1000 experiments that it takes until 10 days of injuries occur. Print this value to the screen with the appropriate labeling information
Source Code in Java:
import java.util.Scanner;
class SafetyAnalysis
{
static boolean isInjury(double p) //method to determine if there is
injury on a particular day
{
double injury=Math.random();
if(injury<p)
return true;
else
return false;
}
static int daysTillTenInjuries(double p) //method to return days
passed till injury occurs on ten days in the period
{
int days=0,injuries=0;
while(injuries<10)
{
if(isInjury(p))
injuries++;
days++;
}
return days;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the value of p: "); //input prompt
double p=in.nextDouble(); //input
if(p>=0 && p<=1); //input validation
else
{
System.out.println("The value of p has to be between 0 and
1!");
return;
}
int total=0;
for(int i=0;i<1000;i++) //running the simulation 1000
times
{
total+=daysTillTenInjuries(p);
}
System.out.println("Average days till 10 injuries: "+total/1000.0);
//output
}
}
Output: