CS 140 - Lab 7, Tuesday Oct 7

Objectives

  1. Drawing a line graph
  2. Simulate a random process such as gambling or financial markets.

Gambler's Ruin Lab

Create a new Java class named Lab7 and save it to your P: drive in a file named Lab7.java. Add a main method and make sure it compiles before you proceed.

To see how your lab will finally look run my version by double clicking on My Computer and going to the folder T:/Harcourt/Fall2008/CS140/Lab7 and then double click on the file run.bat. Click on the black command window and enter the starting dollar amount.

Before you add graphics we'll do this all at the console first.

The Gambler's Ruin

  1. Write a Java program that simulates tossing a fair coin 100 times. Have your program prompt the user with a starting amount that they wish to "invest". As your program runs print to the console the running total of the current amount of cash. Play around with the starting cash amount to satsify yourself that the program is behaving properly.
  2. The Gamblers Ruin says that with any starting cash amount, and you gamble long enough, the gambler always goes broke. Lets verify this. Comment out the print statement in the for loop and replace the for-loop with the following for-loop that runs for ever:
    for(;;) 
    {
    // your code here
    }
    
    The reason we are commenting out the print statement is that your program might need to make a large number of coin tosses and the print statement really slows it down.

    As soon as the amount of cash the gambler has is zero, break the for-loop. Experiment with different starting cash values and see how long it takes to go broke. Of course if you start with values too high the simulation could run for a long time.

Plotting The Gambler's Ruin

In this part of the lab you are going to plot the progress of the gambler as a line graph.

  1. Let the X-axis be the coin toss trial, so if x is 78 that means we are on toss number 78. Let the Y-axes represent the current amount of cash the gambler has.

    Add a 1000 by 600 window to your program and change the for loop so that it makes as many tosses as the window is wide in pixels. Plot the gambler's progress in black.

  2. Add the animated text box in the upper right corner that display's the gambler's current cash amount.
  3. Have your simulation make 10,000 coin tosses. But now only 1000 tosses can fit on the line graph. When we get to the end of the window on the right have your line graph restart at the beginning in a completely new random color.
  4. What happens if the casino (the computer) takes a cut, that is the user only wins a toss 49% of the time.
  5. Make your bets 2 dollars each and adjust the winnings accordingly. Instead of drawing a single pixel what should we draw now?
  6. Lets keep track of the most that we were ever up?
  7. How about the most we were in the hole?