# Monte Carlo Method

• July 22nd, 2010, 01:06 PM
KiwiFlan
Monte Carlo Method
I have to write a program using the Monte Carlo Method to estimate the average number of bottles of Boost someone would have to drink to win a prize.

So far, I have prompted the user for the number of trials (1 trial = the times it takes until the winning cap is found). I have to conduct at least 1,000 trials. The problem is, I can't get it to print correctly. If I want 20 trials, it only prints about 5 numbers, and they are printed in increasing order.

Here is what I have so far:
Code Java:

```//import the classes import java.io.IOException; import java.util.Scanner; import java.io.File; import java.util.Random; public class BottleCapPrize { public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); Random rand = new Random();   int count = 0;   System.out.print("Number of Trials: "); int numTrials = in.nextInt();   //randomly generate the value of the "guessing" cap int randBottleCap = rand.nextInt(5)+1;   //Loop to increment through the number of trials for(int i = 1; i <= numTrials; i++) { int winningCap = rand.nextInt(5)+1;   //check to see if the "guessing" cap is equal to the winning cap if( randBottleCap != winningCap) { count++; randBottleCap = rand.nextInt(5)+1; } else { System.out.println(count); }   } } }```
• July 22nd, 2010, 01:34 PM
Norm
Re: Monte Carlo Method
Quote:

If I want 20 trials, it only prints about 5 numbers, and they are printed in increasing order.
What order are they supposed to be printed in?
Have you tried debugging your program by printing out all the values of variables as they are generated and changed?
Maybe you would see what the problem is.

• July 22nd, 2010, 07:47 PM
KiwiFlan
Re: Monte Carlo Method
Quote:

Originally Posted by Norm
What order are they supposed to be printed in?
Have you tried debugging your program by printing out all the values of variables as they are generated and changed?
Maybe you would see what the problem is.