0

I apologize in advance for my lack of Java knowledge. I am new to Java programming and am trying to make a program where I can flip a coin and count how many times the coin lands on heads within N amount of rolls, measure the time it takes to do so, and then print it out in the Console so that I can save it in a .txt file. I think I've almost gotten it; I'm just having difficulties printing it out now. Any help would be appreciated! I'm stuck!

import java.util.Random;
import java.io.*;

public class RollGraph
{
    public static void flip(int n)
    {
        Random rnd = new Random();
        int roll = 0;
        int countHeads = 0;
        int headsInRow = 0;
        int headsOrTails = rnd.nextInt(2);

        while(roll<n){

            if(headsOrTails == 1){
                countHeads++;
                headsInRow++;
            }
            else{
                headsInRow=0;
            }
        }
        return;
    }

    public static void main(String[] arg) throws IOException
    {
        BufferedWriter writer = new BufferedWriter(
                new FileWriter( new File("data.txt")));
        long start,end,elapsed;
        int repeat = 20;
        double total;
        double average;

        for(int n=1;n<100;n++)
        {
            total = 0.0;
            for(int j=0;j<repeat;j++)
            {
                start = System.nanoTime();
                flip(n);
                end = System.nanoTime();
                elapsed = end - start;
                total += elapsed/1000000;
            }
            average = total/repeat;
            String line = n+"\t"+ average+"\t"+Math.log(average);
            System.out.println(line);
            writer.write(line);
            writer.newLine();
            writer.flush();
        }
        writer.close();
    }
}
4

3 回答 3

0

除了已经提到的无限循环和除法问题,如果你想让你的打印线更干净,我建议你使用BigDecimal来四舍五入你的双打:

String line = n+"\t"+ BigDecimal.valueOf(average).setScale(5, BigDecimal.ROUND_HALF_UP) + "\t"+ BigDecimal.valueOf(Math.log(average)).setScale(5, BigDecimal.ROUND_HALF_UP);
于 2014-02-26T18:57:44.583 回答
0

flip这个循环的方法中while(roll<n){
这里你不增加roll变量。

这是我看到的一个问题。

检查您的flip方法的逻辑。对我来说似乎不对。

于 2014-02-26T18:47:02.047 回答
0

我看到两个问题。首先,你有一个无限循环flip,因为你根本不增加roll。增加它。

其次,你在这一行有整数除法:

total += elapsed/1000000;

在 Java 中,除以两个ints 必须得到一个int,所以你可能会在这里得到一堆零。使用double文字或强制elapsed转换double来执行浮点运算。

total += elapsed/1000000.0;

或者

total += (double) elapsed/1000000;
于 2014-02-26T18:48:59.680 回答