您的位置:首页 > 编程语言 > Java开发

Java生成随机字符串,必须包含数字、小写字母、大写字母

2013-04-01 23:36 791 查看
一道算法题,生成随机字符串,必须包含数字、小写字母、大写字母。

为了生成随机数方便,特别编写StdRandom类(注1),API如下。

public class StdRandom
static double random()0到1之间的实数 [0,1)
static int uniform(int N)0到N-1之间的整数[0,N)
static int uniform(int lo,int hi)lo到hi-1之间的整数[lo,hi)
static double uniform(double lo,double hi)lo到hi之间的实数[lo,hi)
了解了StdRandom类API以后,就来看一下生成随机字符串的RandomStr类是如何完成任务的。(辅助类StdRandom最后介绍。)

RandomStr.java

public class RandomStr {

/**
* 单元测试
* 运行: java RandomStr 4  (生成长度为4的字符串)
*/
public static void main(String[] args){
int len = Integer.parseInt(args[0]);;
System.out.println(randomStr(len));
}

/**
* 返回随机字符串,同时包含数字、大小写字母
* @param len 字符串长度,不能小于3
* @return String 随机字符串
*/
public static String randomStr(int len){
if(len < 3){
throw new IllegalArgumentException("字符串长度不能小于3");
}
//数组,用于存放随机字符
char[] chArr = new char[len];
//为了保证必须包含数字、大小写字母
chArr[0] = (char)('0' + StdRandom.uniform(0,10));
chArr[1] = (char)('A' + StdRandom.uniform(0,26));
chArr[2] = (char)('a' + StdRandom.uniform(0,26));

char[] codes = { '0','1','2','3','4','5','6','7','8','9',
'A','B','C','D','E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z','a','b','c','d',
'e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x',
'y','z'};
//charArr[3..len-1]随机生成codes中的字符
for(int i = 3; i < len; i++){
chArr[i] = codes[StdRandom.uniform(0,codes.length)];
}

//将数组chArr随机排序
for(int i = 0; i < len; i++){
int r = i + StdRandom.uniform(len - i);
char temp = chArr[i];
chArr[i] = chArr[r];
chArr[r] = temp;
}

return new String(chArr);
}
}


看一下辅助类StdRandom。

StdRandom.java

public final class StdRandom {

//随机数生成器
private static Random random;
//种子值
private static long seed;

//静态代码块,初始化种子值及随机数生成器
static {
seed = System.currentTimeMillis();
random = new Random(seed);
}

//私有构造函数,禁止实例化
private StdRandom() {}

/**
* 设置种子值
* @param s 随机数生成器的种子值
*/
public static void setSeed(long s){
seed = s;
random = new Random(seed);
}

/**
* 获取种子值
* @return long 随机数生成器的种子值
*/
public static long getSeed(){
return seed;
}

/**
* 随机返回0到1之间的实数 [0,1)
* @return double 随机数
*/
public static double uniform(){
return random.nextDouble();
}

/**
* 随机返回0到N-1之间的整数 [0,N)
* @param N 上限
* @return int 随机数
*/
public static int uniform(int N){
return random.nextInt(N);
}

/**
* 随机返回0到1之间的实数 [0,1)
* @return double 随机数
*/
public static double random(){
return uniform();
}

/**
* 随机返回a到b-1之间的整数 [a,b)
* @param a 下限
* @param b 上限
* @return int 随机数
*/
public static int uniform(int a,int b){
return a + uniform(b - a);
}

/**
* 随机返回a到b之间的实数
* @param a 下限
* @param b 上限
* @return double 随机数
*/
public static double uniform(double a,double b){
return a + uniform() * (b - a);
}
}


注1:StdRandom类来自《算法(第4版)》 第一章 《基础编程模型》, 作者 Robert Sedgewick 、 Kevin Wayne。本文中的StdRandom类是精简版本,删除了其他未用到的方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐