Random和Math.random

Random

Random:产生随机数的类
构造方法

  • Random();没有种子,使用的是默认种子。是当前时间的毫秒值。
  • Random(long seed);结出有效的种子,给定种子后,每次出现的随机数是相同的。

成员方法

  • public int nextInt();返回的是int范围内的随机数
  • public int nextInt(int n);返回的是(0.n)范围内的随机数,生成的是(0,n)的开区间的数。
  • public double nextDouble();返回下一个伪随机数,它是取自此随机数生成器序列的、在 0.0 和 1.0 之间均匀分布的 double 值
public class RandomTest {
    public static void main(String[] args) {
        //创建对象
//      Random random = new Random();
        Random random = new Random(1111);       
        for(int x= 0 ;x<10;x++) {
            int num = random.nextInt(100)+1;
            System.out.println(num);
        }   
    }
}
结果:27  7  6  70  51  28  26  5  99  17 
public class Demo02Random {
    public static void main(String[] args) {
        Random r = new Random();
        for (int i = 0; i <5 ; i++) {
            System.out.print(r.nextDouble()+"  ");
        }

    }
}
结果:0.0011910175921947541  0.08550604700841791  0.4858359682484331  0.2766477348561561  0.8977107605644782 

Math.random

public static double random();
返回带正号的double值,该值大于等于0.0且小于1.0,。返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。

public class MathDemo {

    public static void main(String[] args) {
        System.out.println("random:"+Math.random());

        System.out.println("random:"+((int) (Math.random()*100)+1));
    }
}

random:0.3166464832091951
random:74

实例:获取start和end之间的随机数:

public static int getRandom(int start , int end) {
    int number = (int)Math.random() * (end-start+1)+start;
    return number;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值