如何在 Java 中計算某個範圍內的隨機數的重複可能性


要獲取某個範圍內的隨機數的重複數字,迴圈遍歷並建立兩個 Random 類物件 −

使用 nextInt() 來獲取下一個數字 −

intrandVal1 = new Random().nextInt(50);
intrandVal2 = new Random().nextInt(50);

現在,比較以上兩個數字 −

if (randVal1 == randVal2) {
   System.out.println("Duplicate number = "+randVal1);
}

以上所有操作都在迴圈中完成 −

for (int i = 1; i <= 50; i++) {
   intrandVal1 = new Random().nextInt(50);
   intrandVal2 = new Random().nextInt(50);
   if (randVal1 == randVal2) {
      System.out.println("Duplicate number = "+randVal1);
   }
}

示例

import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      for (int i = 1; i<= 50; i++) {
         int randVal1 = new Random().nextInt(50);
         int randVal2 = new Random().nextInt(50);
         if (randVal1 == randVal2) {
            System.out.println("Duplicate number = "+randVal1);
         }
      }
   }
}

輸出

Duplicate number = 35
Duplicate number = 28

更新於: 30-Jul-2019

154 次瀏覽

Kickstart Your 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.