`

生成指定位数的随机字符串和数字

 
阅读更多

import java.util.Random;

public class RandomUtils {
	private static Random randGen = null;
	private static char[] numbersAndLetters = null;
	private static Object initLock = new Object();

	/**
	 * int是字符串的长度,即可产生指定长度的随机字符串。
	 * 
	 * @param length
	 * @return
	 */
	public static final String randomString(int length) {

		if (length < 1) {
			return null;
		}
		if (randGen == null) {
			synchronized (initLock) {
				if (randGen == null) {
					randGen = new Random();
					numbersAndLetters = ("~!@#$%^&*()_+.,/?,.<>';0123456789abcdefghijklmnopqrstuvwxyz没有啊啊啊啊啊啊啊啊啊啊啊啊").toCharArray();
					//numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz").toCharArray();
				}
			}
		}
		char[] randBuffer = new char[length];
		for (int i = 0; i < randBuffer.length; i++) {
			randBuffer[i] = numbersAndLetters[randGen.nextInt(36)];
		}
		return new String(randBuffer);
	}
	/**
	 * 产生11位随机数,以1开头,类似手机号
	 * @return
	 */
	public static String getRandomPhone(){
		StringBuffer sb=new StringBuffer();
		for (int i = 0; i < 10; i++) {
			sb.append((int) (10 * (Math.random())));
		}
		return "1"+sb.toString();
	}
	/**
	 * 产生指定位数的数字
	 * @param length
	 * @return
	 */
	public static final String randomNum(int pwd_len) {
		//35是因为数组是从0开始的,26个字母+10个数字
	    final int maxNum = 36;
	    int i; //生成的随机数
	    int count = 0; //生成的密码的长度
	    char[] str = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
	    StringBuffer pwd = new StringBuffer("");
	    Random r = new Random();
	    while(count < pwd_len){
	     //生成随机数,取绝对值,防止生成负数,
	   
	     i = Math.abs(r.nextInt(maxNum)); //生成的数最大为36-1
	   
	     if (i >= 0 && i < str.length) {
	      pwd.append(str[i]);
	      count ++;
	     }
	    }
	    return pwd.toString();
	}
	public static void main(String[] args) {
		System.out.println(randomNum(5));
	}
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics