用Java擲6000次六面骰子


為了用Java擲6000次六面骰子,我們需要使用決策語句對 nextInt() 語句進行宣告。

nextInt() 方法從該隨機數生成器序列中返回下一個隨機整數的值。

宣告 − java.util.Random.nextInt() 方法宣告如下 −

public int nextInt()

讓我們看一個擲6000次六面骰子的程式 −

示例

 線上演示

import java.util.Random;
public class Example {
   public static void main(String args[]) {
      Random rd = new Random(); // random number generator
      int freq[] = new int[6]; // creating an array to compute frequency of each face
      int val;
      int chance = 1;
      // rolling the dice 6000 times
      while(chance <= 6000){
         val = 1 + rd.nextInt(6); // generates integers from 1 to 6
         switch (val) {
            case 1:
               ++freq[0];
               break;
            case 2:
               ++freq[1];
               break;
            case 3:
               ++freq[2];
               break;
            case 4:
               ++freq[3];
               break;
            case 5:
               ++freq[4];
               break;
            case 6:
               ++freq[5];
               break;
         }
         chance++;
      }
      for(int i = 1; i <= 6; i++){
         System.out.println("Side: " + i + "-> Frequency : " + freq[i - 1]);
      }
   }
}

輸出

Side: 1-> Frequency: 987
Side: 2-> Frequency : 971
Side: 3-> Frequency : 1057
Side: 4-> Frequency : 979
Side: 5-> Frequency : 982
Side: 6-> Frequency : 1024

更新於: 25-6月-2020

582次瀏覽

啟動你的 職業

完成課程獲得認證

開始吧
廣告
© . All rights reserved.