Question

I'm really new at this so forgive my ignorance.. So this is what I need to do:

  1. Determine how many bottle caps each person has to open in order to find a winning cap. The answer is 1 in 5.
  2. Prompt the user for the number of trials.
  3. Read back the data for all of the trials from the output file.
  4. Calculate the average number of caps opened in order to win a prize.
  5. Print the result to the screen.

This is what I've tried, but the counter isn't working.. Help?

import java.util.Scanner;
import java.util.Random;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;

public class BottleCapPrize
{
    public static void main(String [] args) throws IOException
    {

        int trials = 0;
        int loop = 1;
        int winCounter = 0;
        int random;
        double average;

        //
        Scanner in = new Scanner(System.in);
        Random rand = new Random();
        PrintWriter outFile = new PrintWriter (new File("MonteCarloMethod.txt"));

        //
        System.out.print("Number of trials: ");
        trials = in.nextInt();

        //
        for(loop = 1; loop <= trials; loop++)
        {
            random = rand.nextInt(5);
            if(random == 1)
            {
                outFile.println("Trial: " + loop + " WIN!");
                winCounter++;
            }
            outFile.println("Trial: " + loop + " LOSE");
        }

        //
        average = winCounter / trials;
        outFile.println("Average number of caps to win: " + average);
        System.out.println("Average number of caps to win: " + average);

        outFile.close();
    }
 }
Was it helpful?

Solution

A problem you may be facing is dividing two int and expecting a double result

int trials = 0;
int winCounter = 0;
double average;

average = winCounter / trials;

What's going to happen divding two int is that you will lose precision. instead make the int into double. Or at least one of them.

double trials = 0;
double winCounter = 0;
double average;

average = winCounter / trials;

And use in.nextDouble()

OTHER TIPS

Actually, your loop/counter is working. What the problem is is that average calculation isn't correct. You need to make sure the division numbers are treated as floats. So either do the below calculation, making sure winCounter and trials are both treated as floats:

average = (float) winCounter / (float) trials;

Or declare winCounter and trials as floats.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top