Java Math random()方法返回一个大于或等于0.0且小于1.0的值。
该andom()方法的语法为:
Math.random()
注意:random()方法是静态方法。因此,我们可以使用类名Math直接调用该方法。
Math.random()方法不带任何参数。
返回介于0.0和1.0之间的伪随机值
注意:返回的值不是真正随机的。 取而代之的是,数值是通过满足某种随机性条件的确定的计算过程来生成的。 因此称为伪随机值。
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()方法返回三个不同的值。
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)将双精度值转换为int。
//Math.round()生成0.0到1.0之间的值
int random = (int)(Math.random() * range) + lowerBound;
System.out.print(random + ", ");
}
}
}
输出结果
10到20之间的随机数:
15, 13, 11, 17, 20, 11, 17, 20, 14, 14,
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 ++) {
// get random array index
int random = (int)(Math.random() * range) + lowerBound;
System.out.print(array[random] + ", ");
}
}
}
输出结果
随机数组元素:
67, 34, 77, 34, 12, 77,