[Java] 生成随机数

方法 1

使用Math.random()函数,范围 [0, 1),包括0, 不包括1double型,不需要import,可以直接使用。例如 (int) (Math.ranom() * 10)返回 [0, 9] 范围内的随机整数,依此类推。
有关Math的其他常用常量及方法如下:

Math.PI
Math.random()
Math.pow(a, b)
Math.abs(a)
Math.max(a, b)
Math.min(a, b)
Math.sqrt(a)
Math.sin(radians)
Math.asin(a)
Math.toRadians(degrees)
Math.toDegress(radians)

方法 2

使用java.util.Random

方法 含义
+Random() Constructs a Random object with the current time as its seed.
+Random(seed: long) Constructs a Random object with a specified seed.
+nextInt(): int Returns a random int value.
+nextInt(n: int): int Returns a random int value between 0 and n (excluding n).
+nextLong(): long Returns a random long value.
+nextDouble(): double Returns a random double value between 0.0 and 1.0 (excluding 1.0).
+nextFloat(): float Returns a random float value between 0.0F and 1.0F (excluding 1.0F).
+nextBoolean(): boolean Returns a random boolean value.

当创建Random对象时, 必须指定种子或使用默认种子,种子是一个用于初始化随机数生成器的数字,无参构造函数使用当前消逝的时间作为种子,如果两个对象种子相同,它们将生成相同的数字序列。例如,下面的代码创建种子同为3的两个Random对象:

Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
    System.out.print(random1.nextInt(1000) + " ");

Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
    System.out.print(random2.nextInt(1000) + " ");

以上代码生成相同的随机整数序列:

From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961

[1] Introduction to Java Programming 10th. 3.7 , 9.6.2, Java Quick Reference

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81214019