随机数频率

时间:2016-01-14 15:43:24

标签: java

我创建了一个由6个数字组成的数组,我随机打印内容100次(模拟掷骰子100次)。现在我想显示打印的每个数字的频率,我遇到了麻烦。任何帮助,将不胜感激。 我已经做了什么:

        int dice;

    int[] diceArray = new int[]{1, 2, 3, 4, 5, 6};

    Random rand = new Random();

    for (int counter = 0; counter < 100; counter++) {
        dice = diceArray[rand.nextInt(diceArray.length)];

2 个答案:

答案 0 :(得分:3)

一种选择是使用具有以下频率的单独阵列:

int[] frequencies = new int[6];

for (int counter = 0; counter < 100; counter++) {
  int index = rand.nextInt(diceArray.length);
  dice = diceArray[index];
  frequencies[index]++;
}

答案 1 :(得分:0)

 Int[] cnt= new int[6]; // Counter for each dice-roll
 for (int i = 0; i<6;i++) cnt[i] = 0; // Make everyone 0
 Random random = new Random(); // To get random numbers
 for (int i = 0; i<100;i++){ // To roll 100 times
      int a = random.nextInt(6 - 1 + 1); // Save your dice Roll
      cnt[a-1]+=1; // to log your frequencies
      System.out.println(a) // to print out
}

没有试过这个,而且我一直在使用java,但这应该有效。如果不是,我很抱歉!