四时宝库

程序员的知识宝库

初学Java,写了一个生成随机密码方法

public class GeneratePasswd  {
	
	// 随机字符串洗牌
	public static String shuffle(char[] c) {
		Random random = new Random();
		
		for (int i = c.length -1; i > 0; i--) {
			int p = random.nextInt(i+1);
			
			char temp = c[i];
			c[i]=c[p];
			c[p]=temp;			
		}
		return String.valueOf(c);
		
	}
	
	/*
	 * 生成字符串数组
	 */
	public static String  generateString(int l,int s,int n) throws Exception {
		
		
		if(l<5) {
			throw new Exception("字符串的长度应该大于5");
		}
		if (l < (s+n)) {
			throw new Exception("字符串中指定的数字和特殊符号的个数不正确");
		}
		if (s < 0||n<0 ) {
			throw new Exception("特殊符号和数字的个数必须为0或者或大于0的正整数");
		}
		
		String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String symbos="!@#$%^&*()_+=<>?";
		String numbers="0123456789";
		Random random = new Random();
		
		char[] randomString = new char[l];
		
		for (int i = 0; i < (l - n - s); i++) {
			randomString[i]=chars.toCharArray()[random.nextInt(chars.length())];
		}
		
		for (int i = 0; i < s; i++) {
			randomString[i + (l-n-s)] = symbos.toCharArray()[random.nextInt(symbos.length())];
		}
		
		for (int i = 0; i < n; i++) {
			randomString[i+(l-n)]=numbers.toCharArray()[random.nextInt(numbers.length())];
		}
		return shuffle(randomString);
	}


}

有什么改进的建议?

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接