在实际应用场景中,获取随机数一般都定义范围内获取。

  • 方法一:Math.random()
public static void main(String[] args) {
        //获取一个(0,100)之间的随机数
        int a = (int) (Math.random() * 100);

        //获取一个(50,100)之间的随机数
        //说明:如果想要产生(50,100)之间的数字,先让它产生(0,50)之间的数字,也就是:random()*50,
        //     然后在后面加上51,也就是random()*50+51,得到的就是(50,100)的整数了。
        int b = (int) (Math.random() * 50) + 51;

        //获取一个(-50,50)之间的随机数
        int c = (int) (Math.random() * 100) - 50;

        //获取一个(-30,150)之间的随机数
        int d = (int) (Math.random() * 180) - 30;

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
    }

位数的随机整数产生方法:

public static void main(String[] args) {
        //生成 4位 随机数:
        System.out.println((int) ((Math.random() * 9 + 1) * 1000));

        //生成 5位 随机数:
        System.out.println((int) ((Math.random() * 9 + 1) * 10000));

        //生成 6位 随机数:
        System.out.println((int) ((Math.random() * 9 + 1) * 100000));
    }

解释:

Math.random() 随机产生浮点范围是 0.0~1.0(包括0不包括1) 之间的数值。
(int) (Math.random() * 9) 随机产生整数范围是 0~9(包括0和9) 之间的数值。
(int) (Math.random() * 9+1) 随机产生整数范围是1~9(包括1和9) 之间的数值。

位数的随机数产生方法:

用法:(数据类型)(Math.random()*(最大值-最小值+1))+最小值

public static void main(String[] args) {
        //生成 4位(1000~9999) 的随机数:
        System.out.println((int) (Math.random() * (9999 - 1000 + 1)) + 1000);
    }
  • 方法二:Random.nextInt()
public static void main(String[] args) {
        //创建Random类对象
        Random random = new Random();

        //获取一个随机数
        int a = random.nextInt();

        //获取(0,50)之间的随机数
        int b = random.nextInt(50);

        //获取(50,100)之间的随机数
        int c = random.nextInt(100 - 50 + 1) + 50;

        //获取一个(-50,50)之间的随机数
        int d = random.nextInt(100) - 50;

        //获取一个(-30,150)之间的随机数
        int e = random.nextInt(180) - 30;

        System.out.println(a);
        System.out.println(b);
        System.out.println(c);
        System.out.println(d);
        System.out.println(e);
    }

作者:BestEternity亲笔。