java生成随机数的两种方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ASJBFJSB/article/details/82453763

1.使用Math类中的Math.random()方法

生成(0.1)区间的数字,因此当需要生成更大范围内的数字,需要在返回值的基础上扩大倍数以回去更大的随机值。

import java.util.Random
public class Main{
    public static void main(String[] args){
        for(int i=0;i<5;++i){
            System.out.println(Math.Random()+" ");
        }
        for(int i=0;i<5;++i){
            //扩大随机数的范围(0,1000)
            System.out.println(1000*Math.Random()+" ");
        }
    }
}


静态成员方法可以通过类调用:
随机生成的结果:
这里写图片描述
这里写图片描述

2.通过Random类定义随机对象
与Math类中的Math.random()方法不同的是,通过Random定义出来的对象,通过对象调用方法。可以获得不同范围内的随机数,而这个范围取决于你给定的范围。此外,获取随机数的类型也更多。

import java.util.Random;
public class Main{
    public static void main(String[] args){
        Random rand = new Random();
        //随机生成[0,1000)区间内的数字
        rand.nextInt(1000);
    }
}

可供选择生成随机数的类型
这里写图片描述

猜你喜欢

转载自blog.csdn.net/ASJBFJSB/article/details/82453763