JAVA随机生成四位数字

Java 生成随机数常用的生成方式:

1、使用Random类,下面的方式可以生成0-10000的整数,不包括10000,但不一定是四位数

Random random = new Random();
System.out.println("---------"+random.nextInt(10000) );

2、Math.random()*9000+1000  或 (int)((Math.random()*9+1)*1000)

System.out.println((int)((Math.random()*9+1)*1000));

   说明:

   Math.random()取值范围是[0,1)
   Math.random()*9000的取值范围是[0,9000);
   Math.random()*9000+1000的取值范围是[1000,10000)。

备注:

     1、Random的那些坑,如下结果永远是一个值

      for(int i =0 ;i<50;i++){
Random random = new Random(10000);
System.out.println("-----------"+random.nextInt(10000) );
}
输出结果:
-----------2208
-----------2208
-----------2208
-----------2208
-----------2208
-----------2208
-----------2208
-----------2208
-----------2208
-----------2208

猜你喜欢

转载自www.cnblogs.com/xuzhujack/p/12630101.html
今日推荐