Java--Random类

2022-10-11  本文已影响0人  李赫尔南

  Math类中虽然为我们提供了产生随机数的方法Math.random(),但是通常我们需要的随机数范围并不是[0, 1)之间的double类型的数据,这就需要对其进行一些复杂的运算。如果使用Math.random()计算过于复杂的话,我们可以使用例外一种方式得到随机数,即Random类,这个类是专门用来生成随机数的,并且Math.random()底层调用的就是Random的nextDouble()方法。

【示例】Random类的常用方法

import java.util.Random;
public class TestRandom {
    public static void main(String[] args) {
        Random rand = new Random();
        //随机生成[0, 1)之间的double类型的数据
        System.out.println(rand.nextDouble());
        //随机生成int类型允许范围之内的整型数据
        System.out.println(rand.nextInt());
        //随机生成[0, 1)之间的float类型的数据
        System.out.println(rand.nextFloat());
        //随机生成false或者true
        System.out.println(rand.nextBoolean());
        //随机生成[0, 10)之间的int类型的数据
        System.out.print(rand.nextInt(10));
        //随机生成[20, 30)之间的int类型的数据
        System.out.print(20 + rand.nextInt(10));
        //随机生成[20, 30)之间的int类型的数据(此种方法计算较为复杂)
        System.out.print(20 + (int) (rand.nextDouble() * 10));
    }
}
上一篇下一篇

猜你喜欢

热点阅读