Java实现获取随机字符串

1.  代码块

import java.util.Random;

/**
 * 随机字符串工具
 * 
 * @author volitation
 *
 */
public class RandomString {

	/**
	 * 获取指定长度随机字符串
	 * 
	 * @param length
	 * @return
	 */
	public static String getRandomString(int length) {
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(3);
			long result = 0;
			switch (number) {
			case 0:
				result = Math.round(Math.random() * 25 + 65);
				sb.append(String.valueOf((char) result));
				break;
			case 1:
				result = Math.round(Math.random() * 25 + 97);
				sb.append(String.valueOf((char) result));
				break;
			case 2:
				sb.append(String.valueOf(new Random().nextInt(10)));
				break;
			}
		}
		return sb.toString();
	}
	
	/**
	 * 测试验证
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(RandomString.getRandomString(5));
		System.out.println(RandomString.getRandomString(10));
		System.out.println(RandomString.getRandomString(15));
	}

}

2.  测试结果 

NVadc
8C1UH1Y0hS
dfiXZMR22pv422I

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页