随机数的产生可用于的场景验证码 密码

一、Random

    通过import java.util.Random包中的Random类创建一个对象

      Random temp = new Random();

      通过 temp对象可以生成一个区间的随机说,temp有很多的方法nextDouble nextInt等,我们如果通过数据字典的方式去生成一个随机串的话,

可以用nextInt去返回一个整数,然后根据下标取值。

二、random

  通过Math.random()来生成随机数,此生成数的返回值区间是0-1之间的小数,可以用此函数来生成随机数,例如:Math.random()*10 指的是0-10之间的小数

 

代码示例:

生成随机长度的一个随机串

public class MyRandom {

public StringBuffer rndom(int t){
final int MAXNUM = 9;
int count = 0;//生成的密码长度
int i;
StringBuffer pwd= new StringBuffer("");
char[] str={'a','b','c','1','2','3','4','5','6'};

Random temp = new Random();
System.out.println((int)(Math.random()*10));
while(count < t){
i=Math.abs(temp.nextInt(MAXNUM));//生成随机数

if(i >= 0 && i < str.length){
pwd.append(str[i]);
count++;
}
}
return pwd;
}
}

 

posted @ 2017-04-11 18:11  ThrownBug  阅读(191)  评论(0编辑  收藏  举报