蛇眼滚动2骰子的仿真及JAVA平均值的计算

时间:2018-04-24 06:29:29

标签: java loops for-loop simulation

因此,我必须使用for循环编写两个骰子滚动1000次的模拟,并计算蛇眼发生的平均值。 到目前为止,我得到了:

public class RollDiceforloop {
    public static void main(String[] args) {

        int die1, die2, snakeye, rolls;
        snakeye = 0;

        die1 = 0;
        die2 = 0;

        for (rolls = 0; rolls < 1000; rolls++) {
            die1 = (int)(Math.random() * 6) + 1;
            die2 = (int)(Math.random() * 6) + 1;
            if (die1 != 1 && die2 != 1); {

            }
            if (die1 == 1 && die2 == 1) {
                snakeye +=1;
            }
        }
        TextIO.putln(""+snakeye+" snake eyes over "+rolls+" rolls of the dice.");
    }
}

我没有计算平均值,因为我想确保我做得对。我的蛇眼数量非常少......我的循环是否正确?

2 个答案:

答案 0 :(得分:0)

我认为你的循环工作得非常好,并为这两个骰子制作1000个随机数 并且你以奇怪的方式计算时间的数量(它会工作但不是有效的)这样做更好,我也计算平均值

public class RollDiceforloop {
    public static void main(String[] args) {
        int die1, die2, snakeye, rolls;
        snakeye = 0;

        die1 = 0;
        die2 = 0;

        for (rolls = 0; rolls < 1000; rolls++) {
            die1 = (int) (Math.random() * 6) + 1;
            die2 = (int) (Math.random() * 6) + 1;
            if (die1 == 1 && die2 == 1) {
                snakeye += 1;
            }
        }
        TextIO.putln("" + snakeye + " snake eyes over " + rolls + " rolls of the dice.");
        TextIO.putln("" + snakeye / 1000.0 + " the average for  " + rolls + " rolls of the dice.");
    }
}

答案 1 :(得分:0)

它是人为的但使用Java8

System.out.println(IntStream.range(0, 1000)               
                .mapToObj(x -> new Tuple((int)(Math.random() * 6) + 1, (int)(Math.random() * 6) + 1))
                .filter(x -> x.a == 1 && x.b == 1)
                .count()); 

public static class Tuple
    {
        final int a;
        final int b;
        Tuple(int a, int b)
        {
            this.a = a;
            this.b = b;
        }
    }