跳到主要内容

Java Math.random() 方法

random() 方法返回一个大于等于 0.0 且小于 1.0 的随机值。

示例

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

// 生成一个 0 到 1 之间的随机数
System.out.println(Math.random());

}
}

// 输出:0.3034966869965544

Math.random() 的语法

random() 方法的语法是:

Math.random()

注意random() 方法是一个静态方法。因此,我们可以直接使用类名 Math 来调用该方法。

random() 参数

Math.random() 方法不接受任何参数。

random() 返回值

  • 返回一个介于 0.01.0 之间的伪随机值

注意:返回的值并非真正的随机数。相反,这些值是由一个确定的计算过程生成的,满足一定的随机性条件。因此被称为伪随机值。

示例 1:Java Math.random()

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

// Math.random()
// 第一个随机值
System.out.println(Math.random()); // 0.45950063688194265

// 第二个随机值
System.out.println(Math.random()); // 0.3388581014886102

// 第三个随机值
System.out.println(Math.random()); // 0.8002849308960158

}
}

在上面的示例中,我们可以看到 random() 方法返回了三个不同的值。

示例 2:生成 10 到 20 之间的随机数

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

int upperBound = 20;
int lowerBound = 10;

// 上界 20 也会被包含
int range = (upperBound - lowerBound) + 1;

System.out.println("10 到 20 之间的随机数:");

for (int i = 0; i < 10; i ++) {

// 生成随机数
// (int) 将 double 值转换为 int
// Math.random() 生成 0.0 到 1.0 之间的值
int random = (int)(Math.random() * range) + lowerBound;

System.out.print(random + ", ");
}

}
}

输出

1020 之间的随机数:
15, 13, 11, 17, 20, 11, 17, 20, 14, 14,

示例 3:访问随机数组元素

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

// 创建一个数组
int[] array = {34, 12, 44, 9, 67, 77, 98, 111};

int lowerBound = 0;
int upperBound = array.length;

// array.length 将被排除
int range = upperBound - lowerBound;

System.out.println("随机数组元素:");
// 访问 5 个随机数组元素
for (int i = 0; i <= 5; i ++) {

// 获取随机数组索引
int random = (int)(Math.random() * range) + lowerBound;

System.out.print(array[random] + ", ");
}

}
}

输出

随机数组元素:
67, 34, 77, 34, 12, 77,

推荐教程