package cn.czxy.test05;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.HashSet;
/**
* 要求产生10个随机的字符串,每一个字符串互相不重复,
* 每一个字符串中组成的字符(a-zA-Z0-9)也不相同,每个字符串长度为10;
* @author dmt
*
*/
public class Test1 {
public static void main(String[] args) {
/**
* step1:先生成一个长度为10的字符串,该字符串由字母或数字构成且每个字符互不相同
* 思路:互不相同,我们可以生成一个HashSet,往里面添加十个字符即可,根据HashSet的特性,里面的每个字符都是
* 互不相同的
*/
HashSet<Character> set = new HashSet<Character>();
ArrayList<Character> list = new ArrayList<Character>();
//将小写字母添加到List a中
for(char a = 'a'; a < 'z'; a++)
{
list.add(new Character(a));
}
//将大写字母添加到List a中
for(char a = 'A'; a < 'Z'; a++)
{
list.add(new Character(a));
}
//将数字添加到List a中
for(char a = '0'; a < '9'; a++)
{
list.add(new Character(a));
}
//list中包括了所有的大小写字母和数字,现在要将list中的字符随机添加到set中
int i = list.size();//i保存了list的元素个数
while(set.size() < 10)//该循环每次从list中随机取一个字符,添加到set中,直到set的长度为10。根据set特性,这10个添进来的字母肯定不重复
{
int j = (int)(Math.random() * (i));//[0,62)
set.add(list.get(j));
}
String s = "";
for(Character c : set)
{
//System.out.print(c);
//将set中的字符组成一个字符串
s = s + c.toString();
}
System.out.println(s);
/*
* step2:要求产生10个随机的字符串,每一个字符串互相不重复,
*/
}
}
* 要求产生10个随机的字符串,每一个字符串互相不重复,
* 每一个字符串中组成的字符(a-zA-Z0-9)也不相同,每个字符串长度为10;
* @author dmt
*
*/
public class Test1 {
public static void main(String[] args) {
/**
* step1:先生成一个长度为10的字符串,该字符串由字母或数字构成且每个字符互不相同
* 思路:互不相同,我们可以生成一个HashSet,往里面添加十个字符即可,根据HashSet的特性,里面的每个字符都是
* 互不相同的
*/
HashSet<Character> set = new HashSet<Character>();
ArrayList<Character> list = new ArrayList<Character>();
//将小写字母添加到List a中
for(char a = 'a'; a < 'z'; a++)
{
list.add(new Character(a));
}
//将大写字母添加到List a中
for(char a = 'A'; a < 'Z'; a++)
{
list.add(new Character(a));
}
//将数字添加到List a中
for(char a = '0'; a < '9'; a++)
{
list.add(new Character(a));
}
//list中包括了所有的大小写字母和数字,现在要将list中的字符随机添加到set中
int i = list.size();//i保存了list的元素个数
while(set.size() < 10)//该循环每次从list中随机取一个字符,添加到set中,直到set的长度为10。根据set特性,这10个添进来的字母肯定不重复
{
int j = (int)(Math.random() * (i));//[0,62)
set.add(list.get(j));
}
String s = "";
for(Character c : set)
{
//System.out.print(c);
//将set中的字符组成一个字符串
s = s + c.toString();
}
System.out.println(s);
/*
* step2:要求产生10个随机的字符串,每一个字符串互相不重复,
*/
}
}