在 Java 中生成隨機數


使用三種方式可以在 Java 中生成隨機數。

  • 使用 java.util.Random 類 − 可以使用 Random 類物件使用 nextInt()、nextDouble() 等方法生成隨機數。

  • 使用 java.lang.Math 類 − Math.random() 方法在每次呼叫時返回一個隨機雙精度數。

  • 使用 java.util.concurrent.ThreadLocalRandom 類 − ThreadLocalRandom.current().nextInt() 方法及類似的其他方法在每次呼叫時返回一個隨機數。

例子

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

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

      generateUsingRandom();
      generateUsingMathRandom();
      generateUsingThreadLocalRandom();
   }

   private static void generateUsingRandom() {
      Random random = new Random();
      //print a random int within range of 0 to 10.
      System.out.println(random.nextInt(10));

      //print a random int
      System.out.println(random.nextInt());

      //print a random double
      System.out.println(random.nextDouble());
   }

   private static void generateUsingMathRandom() {
      //print a random double
      System.out.println(Math.random());
   }

   private static void generateUsingThreadLocalRandom() {
      //print a random int within range of 0 to 10.
      System.out.println(ThreadLocalRandom.current().nextInt(10));

      //print a random int
      System.out.println(ThreadLocalRandom.current().nextInt());

      //print a random double
      System.out.println(ThreadLocalRandom.current().nextDouble());

   }
}

輸出

9
-1997411886
0.7272728969835154
0.9400193333973254
6
852518482
0.13628495782770622

更新於:21-6月-2020

1K+ 瀏覽

開啟你的 職業生涯

完成該課程以獲得認證

開始
廣告