项目中时长用到不同长度的随机数,这里简要说明一些方法。
【1】Random
代码实例一如下:
Random random = new Random(); int nextInt = random.nextInt();
其nextInt()的JavaDoc如下:
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 2 32(The 32 square of 2) possible int values are produced with (approximately) equal probability.
从随机数生成序列中返回下一个伪随机,均匀分布的int 值。2的32次方在内的int值返回的概率是相等的。
代码实例一如下:
Random random = new Random(); int nextInt2 = random.nextInt(10); System.out.println(nextInt2);
其nextInt(10)的JavaDoc如下:
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All bound possible int values are produced with (approximately) equal probability.
主要意思 : 返回 0-指定值区间的一个int 值 ,用区间表示即 [0 , end)。如nextInt(10)返回区间 [0 , 10)。
举例如返回六位随机数:
Random random = new Random(); int nextInt2 = random.nextInt(10)+100000;
这样返回的相同数概率太大了,换成如下方法:
Random random = new Random(); StringBuilder stringBuilder = new StringBuilder(); for(int i=1;i<7;i++){ int nextInt2 = random.nextInt(10); stringBuilder.append(String.valueOf(nextInt2)); } System.out.println(stringBuilder.toString());
或者试试如下方法:
String sources = "0123456789"; // 加上一些字母,就可以生成pc站的验证码了 Random rand = new Random(); StringBuffer flag = new StringBuffer(); for (int j = 0; j < 6; j++){ flag.append(String.valueOf(sources.charAt(rand.nextInt(9)))); } System.out.println(flag.toString());
【2】Math.random()
代码实例一如下:
double random = Math.random(); System.out.println(random);
其random()的Javadoc如下:
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.
主要意思: 从指定范围大约均匀分布的值中伪随机选择一个返回,该值为区间在[0.0 , 1.0)之间的double值。
举例如返回六位随机数:
int a=(int) ((Math.random()*9+1)*100000); System.out.println(a);