Java中Random类的使用介绍

王林
王林 转载
2020-07-17 16:49:44 2203浏览

Random类介绍

(推荐教程:java入门教程

Random类专门用于生成一个伪随机数,它有两个构造器:一个构造器使用默认的种子(以当前时间作为种子),另一个构造器需要程序员显式传入一个long型整数的种子。

Random类比Math类的random()方法提供了更多的方式来生成各种伪随机数,可以生成浮点类型的伪随机数,也可以生成整数类型的伪随机数,还可以指定生成随机数的范围。

构造函数:

public Random()    //int范围内的随机数
public Random(long seed)

代码实现:

1、产生一个随机数。

import java.util.Random;

public class Test01 {
    public static void main(String[] args) {
        // 创建随机数对象
        Random random = new Random();

        // 随机产生一个int范围内的数字
        int num1 = random.nextInt();
        System.out.println(num1);  // 范围为[Integer.MIN_VALUE, Integer.MAX_VALUE]之间的一个整数

        // 如果我要产生[0, 100]之间的整数怎么办
        int num2 = random.nextInt(101);
        System.out.println(num2);  // [0, 100]内的一个整数
        // 注意:nextInt(101)翻译为,下一个int类型的数据是101,表示只能取到100

    }
}

(视频教程推荐:java视频教程

2、产生[-100, 100]之间的随机数

public class Test02 {
    public static void main(String[] args) {
        // 创建随机数对象
        Random random = new Random();

        // 打印一千个
        for (int i = 0; i < 1000; i++) {
            // 随机控制正负号,-1的0次方为1,-1的1次方为-1
            int fuhao = random.nextInt(2);  // 0或1
            fuhao = (fuhao == 0) ? 1 : -1;

            int num3 = random.nextInt(101) * fuhao;
            System.out.println(num3);
        }
    }
}

以上就是Java中Random类的使用介绍的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:csdn,如有侵犯,请联系admin@php.cn删除