要求:
1、随机产生2-10位不等的并且只包含和必须包含数字和字母的字符串99条;
2、存储到线程安全的集合中;
3、使用单例模式;
4、对字符串进行排序;
5、把结果打印到控制台,每四个字符串为一行。
package random.test.random;
import java.util.Random;
import java.util.Vector;
/**
*
* @author RoseMary
*
*/
public class CreateRandomNum
{
//单例模式
private static CreateRandomNum instance=null;
public static synchronized CreateRandomNum getInstance()
{
if(instance==null)
{
instance=new CreateRandomNum();
}
return instance;
}
// 生成1條隨機字符串
public String RandomString()
{
StringBuffer sbString = new StringBuffer();
Random random = new Random();
//隨機生成字符串的長度
int randomLength = random.nextInt(10);
for (int i = 0; i < randomLength; i++)
{
int singleRandom = (int) (Math.random() * 100);
// 对不符合要求的数字进行处理
if (singleRandom >= 0 && singleRandom < 24)
{
sbString.append((char) (singleRandom + 65));
}
// 对不符合要求的数字进行处理
if (singleRandom >= 24 && singleRandom < 48)
{
sbString.append((char) (singleRandom + 73));
}
// 48~57数字
if (singleRandom >= 48 && singleRandom < 58)
{
sbString.append((char) (singleRandom));
}
// 对不符合要求的数字进行处理
if (singleRandom >= 58 && singleRandom < 65)
{
sbString.append((char) (singleRandom - 10));
}
// 65~90大写字母
if (singleRandom >= 65 && singleRandom < 91)
{
sbString.append((char) (singleRandom));
}
// 对不符合要求的数字进行处理
if (singleRandom >= 91 && singleRandom < 97)
{
singleRandom = singleRandom - 43;
}
// 97~122小写字母
if (singleRandom >= 97 && singleRandom < 123)
{
sbString.append((char) (singleRandom));
}
}
if(sbString.toString().length()==1||sbString.toString().length()==0)
{
sbString.append((char)(random.nextInt(26)+65)).append((char)(random.nextInt(26)+97));
}
return sbString.toString();
}
//生成99条随机字符串排序,并放入集合中
public Vector<String> getRandomString()
{
String[] strRandom = new String[99];
Vector<String> vector = new Vector<String>();
for (int i = 0; i < 99; i++)
{
strRandom[i] = this.RandomString();
}
//对字符串进行冒泡排序
for (int i=0;i<99-1;i++)
{
for (int j=0;j<99-i-1;j++)
{
if(strRandom[j].compareTo(strRandom[j+1])>0)
{
String temp;
temp=strRandom[j];
strRandom[j]=strRandom[j+1];
strRandom[j+1]=temp;
}
}
}
//放入线性安全的集合
for (int i = 0; i < 99; i++)
{
vector.add(strRandom[i]);
}
return vector;
}
}
package random.test.random;
import java.util.Vector;
public class RandomStringTest
{
public static void main(String[] args)
{
int count = 0;
CreateRandomNum instance = CreateRandomNum.getInstance();
Vector<String> vector = instance.getRandomString();
for (String string : vector)
{
if (count==4)
{
System.out.println("");
count=0;
}
else
{
System.out.print(string + " ");
count++;
}
for (int i = 0; i < 10 - string.length(); i++)
{
if(count!=0)
{
System.out.print(" ");
}
}
}
}
}