java生成随机数(字符串)示例分享
用来生成简单的随机java生成随机数,大小+数字。没特符
代码如下:
package passwords;
import java.util.Random;
public class pwdGen {
private Random rdseed=new Random();
/**
*@param
*length password length;
*@param
*letters boolean non-capital letters combination control;
*@param
*letters_capi boolean capital letters combination control;
*@param
*numbers boolean capital letters combination control;
*/
public String getpwd(int length,boolean letters,boolean letters_capi,boolean numbers){
String res="";
Random rd=this.rdseed;
while(length-->0){
char _1dgt=0;
if(letters&&letters_capi&&numbers){
int _key=rd.nextInt(3);
if(2==_key){
_1dgt=get_L();
}else if(1==_key){
_1dgt=get_L_C();
}else if(0==_key){
_1dgt=get_N();
}
}else if(letters&&letters_capi&&!numbers){
int _key=rd.nextInt(2);
if(1==_key){
_1dgt=get_L();
}else if(0==_key){
_1dgt=get_L_C();
}
}else if(!letters&&letters_capi&&numbers){
int _key=rd.nextInt(2);
if(1==_key){
_1dgt=get_N();
}else if(0==_key){
_1dgt=get_L_C();
}
}else if(letters&&!letters_capi&&numbers){
int _key=rd.nextInt(2);
if(1==_key){
_1dgt=get_L();
}else if(0==_key){
_1dgt=get_N();
}
}else if(letters&&!letters_capi&&!numbers){
_1dgt=get_L();
}else if(!letters&&!letters_capi&&numbers){
_1dgt=get_N();
}else if(!letters&&letters_capi&&!numbers){
_1dgt=get_L_C();
}else{
res=null;
break;
}
res+=_1dgt;
}
return res ;
}
private char get_L_C(){
Random rd=this.rdseed;
int _dgt=(rd.nextInt(26)+65);
return (char)_dgt;
}
private char get_N(){
Random rd=this.rdseed;
int _dgt=(rd.nextInt(10)+48);
return (char)_dgt;
}
private char get_L(){
Random rd=this.rdseed;
int _dgt=(rd.nextInt(26)+97);
return (char)_dgt;
}
private char get_S(){
Random rd=this.rdseed;
int _dgt=(rd.nextInt(14)+33);
return (char)_dgt;
}
public static void main(String[] args) {
pwdGen test= new pwdGen();
int testct=1000000;
long start=System.nanoTime();
while(testct-->0){
test.getpwd(10, true, true, true);
}
long end= System.nanoTime();
System.out.println(((double)(end-start))/(1000000000));
System.out.println(test.getpwd(10, true, true, true));
}
}