JAVA获取随机数的方式

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

  • 方法一: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亲笔。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值