首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java中获取指定位数的随机数目字

2014-01-17 
java中获取指定位数的随机数字/*** 获取一个指定位数的随机码* @return*/public static String getRandomC

java中获取指定位数的随机数字

/**

* 获取一个指定位数的随机码

* @return

*/

public static String getRandomCodeStr(Integer length){

Set<Integer> set = getRandomNumber(length); ??

// 使用迭代器 ??

Iterator<Integer> iterator = set.iterator(); ??

// 临时记录数据 ??

String temp = ""; ??

while (iterator.hasNext()) { ??

temp += iterator.next(); ? ? ?

}

return temp;

}

/** ?

* 获取一个四位随机数,并且四位数不重复 ?

* ??

*?@return Set<Integer> ?

*/ ?

private static Set<Integer> getRandomNumber(Integer length) { ??

? ?// 使用SET以此保证写入的数据不重复 ??

Set<Integer> set = new HashSet<Integer>(); ??

// 随机数 ??

Random random = new Random(); ??

? ? ?

while (set.size() < length) { ??

// nextInt返回一个伪随机数,它是取自此随机数生成器序列的、在 0(包括) ??

// 和指定值(不包括)之间均匀分布的 int 值。 ??

set.add(random.nextInt(10)); ??

} ??

return set; ??

}?

热点排行