CS 140 - Homework 9 - Due Monday March 10


In this homework assignment you are going to write a program that simulates tossing a coin and output some results of the simulation. This homework is a little more work than past assignments and as such will be worth two homework grades (or a possible four homework points).

Java contains a class method named Math.random() that returns a random number between 0 and 1 exclusive (never 0 and never 1). For example, when I run the code:

    double x = Math.random();
    System.out.println("x is " + x);

It prints x is 0.22880378352090058. If a I run it again it prints x is 0.6127417824851569.

About half of the time Math.random() returns a number less than 0.5 and about half of the time it returns a number greater than 0.5.

Write a Java program that reads an integer from the user, stores it in a variable named num_tosses, and simulates tossing a coin num_tosses times. Your program should print an H when a head is tossed and a T when a tail is tossed. It should also keep track of and print the number of heads and tails thrown and the percentage of heads and tails thrown. Below is an example run of my solution. Your's should look similar.

  Enter number of times to toss coin: 20
  HTTHTTTTHTHHTHHTTHTT
  Heads tossed = 8
  Tails tossed = 12
  Percent heads = 40.0
  Percent tails = 60.0

What to turn in

  1. Turn in a printout of your program with your name on it. Your program class should be named HW9.
  2. e-mail me your program as an attachment with the subject heading CS140 HW9.