当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Java Math.random()用法及代码示例

在本教程中,我们将借助示例了解 Java Math.random() 方法。

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()参数

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

random() 返回值

  • 返回之间的伪随机值0.01.0

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

示例 1:Java 数学。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.random() 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,

相关用法


注:本文由纯净天空筛选整理自 Java Math.random()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。