random()
方法返回一个大于或等于 0.0 且小于 1.0 的随机值。
示例
class Main { public static void main(String[] args) { // generates a random number between 0 to 1 System.out.println(Math.random()); } } // Output: 0.3034966869965544
Math.random() 的语法
random()
方法的语法是:
Math.random()
注意: random() 方法是一个静态方法。因此,我们可以使用类名 Math 直接调用该方法。
random() 参数
Math.random()
方法不带任何参数。
random() 返回值
返回一个介于 0.0 和 1.0 之间的伪随机值
注意: 返回的值并不是真正随机的。相反,值是由满足某些随机性条件的确定计算过程生成的。因此称为伪随机值。
示例 1: Java Math.random()
class Main { public static void main(String[] args) { // Math.random() // first random value System.out.println(Math.random()); // 0.45950063688194265 // second random value System.out.println(Math.random()); // 0.3388581014886102 // third random value 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; // upperBound 20 will also be included int range = (upperBound-lowerBound) + 1; System.out.println("Random Numbers between 10 and 20:"); for (int i = 0; i < 10; i ++) { // generate random number // (int) convert double value to int // Math.round() generate value between 0.0 and 1.0 int random = (int)(Math.random() * range) + lowerBound; System.out.print(random + ", "); } } }
输出
Random Numbers between 10 and 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,
示例 3: 访问随机数组元素
class Main { public static void main(String[] args) { // create an array int[] array = {34, 12, 44, 9, 67, 77, 98, 111}; int lowerBound = 0; int upperBound = array.length; // array.length will excluded int range = upperBound-lowerBound; System.out.println("Random Array Elements:"); // access 5 random array elements for (int i = 0; i <= 5; i ++) { // get random array index int random = (int)(Math.random() * range) + lowerBound; System.out.print(array[random] + ", "); } } }
输出
Random Array Elements: 67, 34, 77, 34, 12, 77,