专注Java教育14年 全国咨询/投诉热线:444-1124-454
赢咖4LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 Java产生随机数的方法

Java产生随机数的方法

更新时间:2022-12-15 11:11:35 来源:赢咖4 浏览862次

通常情况下,我们会提出生成随机数或生成范围内随机数的 2 类需求。Java 支持通过ThreadLocalRandom, java.lang.Math和java.util.Random类生成随机数。让我们看看有哪些不同的选项以及如何在Java生成随机数

1.使用ThreadLocalRandom生成随机数

如果您使用的是 Java 1.7 或更高版本,ThreadLocalRandom应该是您在 Java 中生成随机数的标准方法。在 Java 或任何其他语言中生成随机数时可以有 2 种变体。

生成没有范围的随机数。

生成给定范围内的随机数。

package com.javadevjournal.date;
import java.util.concurrent.ThreadLocalRandom;
public class RandomNumberGeneration {
    public static void main(String[] args) {
        int lowerBound = 4;
        int upperBound = 20;
        int random_int = ThreadLocalRandom.current().nextInt(); //returns pseudorandom value
        System.out.println(random_int); //output will be different on different machine (2063277431 while running example);
        /*generate random int within given range between 0 upper given bound.
         * The upper bound is non exclusive i'e it will not be counted while generating the
         * random number.
         * */
        int random_int_with_upper_bound = ThreadLocalRandom.current().nextInt(upperBound);
        System.out.println(random_int_with_upper_bound); // 6 while we were running the code.
        /**
         * Generate random number with a given range of lower and upper bound.
         */
        int random_int_range = ThreadLocalRandom.current().nextInt(lowerBound, upperBound + 1);
        System.out.println(random_int_range); // 18 while we were running the code.
    }
}

使用时请记住以下要点ThreadLocalRandom。

如果您不提供下限,则下限为 0。

上限是非排他性的,如果要在随机数生成中添加上限(将上限加 1 以包含它),则需要小心。

我们不需要对ThreadLocalRandom类进行显式初始化。

如果绑定是<=0,它将抛出IllegalArgumentException。

如果下限大于或等于上限,类将抛出IllegalArgumentException。

int lowerBound = 4;
int upperBound = 3;
/**
  * These will throw IllegalArgumentException.
*/
ThreadLocalRandom.current().nextInt(lowerBound, upperBound);
ThreadLocalRandom.current().nextInt(0);

nextDouble()andnextFloat()方法允许生成 float 和 double 值。它的工作方式类似于上面的示例,我们可以在生成随机 double 或 float 数字时传递下限和上限。

ThreadLocalRandom.current().nextDouble();
ThreadLocalRandom.current().nextDouble(1.0, 34.0);
ThreadLocalRandom.current().nextFloat();

2.使用随机类

如果您使用的不是 Java 1.7 或更高版本,我们可以使用java.util.Random该类在 Java 中生成随机数。以下是该类的一些详细信息:

nextInt(upperBound) – Generate random int between 0 and upperbound -1;

nextFloat() – Generate float between 0.0 to 1.0.

nextDouble() – Generate double between 0.0 to 1.0.

package com.javadevjournal.date;
import java.util.Random;
public class RandomNumberGeneration {
    public static void main(String[] args) {
        int min = 1;
        int max = 67;
        Random random = new Random();
        //Get random int between [0-66]
        int randomInt = random.nextInt(max);
        /*
         If we want to include 67 in the range, add 1 to the upper bound
         i.e max+1
          generate random int between [0- 67]
         */
        int upperBoundInt = random.nextInt(max + 1);
        //another variation
        int randomNum = random.nextInt((max - min) + 1) + min;
        //Double random number
        double randomDouble = random.nextDouble();
        float randomFloat = random.nextFloat();
    }
}

3. 使用 Math.random

如果我们只需要整数或浮点随机值,我们可以使用 Math.random。这是来自Math.random类的示例代码:

double random = Math.random();

这将返回大于或等于0.0且小于的正双精度值1.0。在许多用例中,我们可能希望在给定范围内生成随机数。其中一种选择是使用以下表达式

<前>Math.random() * ((max - min) + 1)) +min

Math.random()在范围内生成双精度值 [0,1)。

要获得特定范围的值,我们应该乘以我们想要覆盖的值范围的大小 ( * ( Max - Min ))。

将此范围向上移动到您的目标范围。您可以通过添加最小值(表达式的最后一部分+min)来做到这一点

public class RandomNumberGeneration {
    public static void main(String[] args) {
        double min = 1;
        double max = 67;
        /*
         Generate random number with in given range
         */
        double random = (int)(Math.random() * ((max - min) + 1));
        System.out.println(random);
    }
}

4. Math.random() 与 Random.nextInt(int)

如果您只对将 int 作为随机数感兴趣,您应该选择 ,Random.nextInt(n)因为此选项更有效且偏差更小。以下是使用Random.nextInt over的一些优点Math.random()

Math.random()在内部使用Random.nextDouble()。最好使用原始的而不是通过它进行路由。

Random.nextInt(n)是可重复的。我们可以通过传递相同的种子来创建 2 个不同的随机对象。

Math.random()也需要大约两倍的处理,并且需要同步。

5. 使用 Java 8 生成随机数

虽然大多数情况可以使用 轻松完成,但是,如果您对如何在 Java 8ThreadLocalRandom中生成随机数更感兴趣 ,这里有几个选项可以使用Java 8完成它。

import java.util.Random;
import java.util.SplittableRandom;
import java.util.stream.IntStream;
public class RandomNumberGeneration {
    public static void main(String[] args) {
        int min = 1;
        int max = 67;
        int size=50;
        /*
          return int between the specified
         * min range (inclusive) and the specified upper bound (exclusive).
         */
        int randomInt= new SplittableRandom().nextInt(min, max);
        //TO return stream of random values
        IntStream stream = new SplittableRandom().ints(size, min, max);
        // to generate int[]
        int[] randomArray= new SplittableRandom().ints(size, min, max).toArray();
        int[] randomArray1= new Random().ints(size, min,max).toArray();
    }
}

以上就是关于“Java产生随机数的方法”介绍,大家如果想了解更多相关知识,不妨来关注一下赢咖4的Java赢咖4在线学习,里面的课程内容细致全面,很适合没有基础的小伙伴学习,希望对大家能够有所帮助。

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>