java生成随机数总结

import java.util.*;

public class RandomDemo{
  public static void main(String[] args){


      /*
         Math.random()的随机数范围为0<=n<1,即:[0,1) 
      */
      double d1 = Math.random();
      System.out.println(d1);
/*
0.13588173801188785
*/    
  
    /*
      生成4位随机整数   
    */
    int i4 = (int)(Math.random()*9000)+1000;
    System.out.println(i4); 
/*
6287
*/ 

    /*
      Math取整数的几个方法说明:
      Math.floor 向下取整(不大于参数的最大整数 )
      Math.ceil 向上取整(不小于参数的最大整数 )
      math.round  四舍五入取整(算法为Math.floor(x+0.5))
    */
    System.out.println(Math.floor(2.5)); 
    System.out.println(Math.floor(-2.5)); 
    System.out.println(Math.ceil(2.5)); 
    System.out.println(Math.ceil(-2.5)); 
    System.out.println(Math.round(2.5)); 
    System.out.println(Math.round(-2.5)); 
/*
2.0
-3.0
3.0
-2.0
3
-2
*/ 


      Random r = new Random();

     /* 
        public boolean nextBoolean();
        随机数范围为:false、true
     */
      boolean b1 = r.nextBoolean();
      System.out.println(b1);
/*
false
*/ 

     /* 
        public int nextInt();
        随机数范围为: int的区间
     */
      int i1 = r.nextInt();
      System.out.println(i1);
/*
-1098866320
*/ 

     /* 
        public long nextLong();
        随机数范围为: long的区间
     */
      long l1 = r.nextLong();
      System.out.println(l1);
/*
8115353135541459577
*/ 

     /* 
        public int nextInt(int n);
        随机数范围为:[0,n)
     */
      int i2 = r.nextInt(100);
      System.out.println(i2); 
/*
71
*/ 

     /* 
        public float nextFloat();
        随机数范围为:[0,1)
     */
      float f1 = r.nextFloat();
      System.out.println(f1);
/*
0.42610747
*/ 


     /* 
        public double nextDouble();
        随机数范围为:[0,1)
     */
      double d2 = r.nextDouble();
      System.out.println(d2);
/*
0.28172834985842776
*/ 


     /* 
        public void setSeed(long seed)
        设置在种子数的基础上进行一定的变换产生随机数。
        相同种子数的Random对象,相同次数生成的随机数字是完全相同的。即第1次生成的随机数相同  

      ,第2次生成的随机数也相同,......,第n次生成的随机数也相同。
     */
     Date date = new Date();
     long time = date.getTime();
     Random r2 = new Random();
     Random r3 = new Random();
     r2.setSeed(time);
     r3.setSeed(time);
     int i21 = r2.nextInt(100);
     int i22 = r2.nextInt(100);
     int i23 = r2.nextInt(100);
     int i31 = r3.nextInt(100);
     int i32 = r3.nextInt(100);
     int i33 = r3.nextInt(100);
     System.out.println(i21 + " " + i22 + " " + i23); 
     System.out.println(i31 + " " + i32 + " " + i33); 
/*
96 57 5
96 57 5
*/ 

  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值