在 Java 中生成隨機數
我可以在 Java 中使用三種方法生成隨機數。
使用 java.util.Random 類 − 可以使用 Random 類的物件使用 nextInt()、nextDouble() 等方法生成隨機數。
使用 java.lang.Math 類 − Math.random() 方法被呼叫時返回一個隨機 double。
使用 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
廣告