I'm really new at this so forgive my ignorance.. So this is what I need to do:
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();
}
}
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()
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.