package?com.ppcc.sortDemo;
import?java.util.ArrayList;
import?java.util.Collections;
import?java.util.Random;
/**
?*?隨機產生一個長度在10以內的字符串,并進行排序
?*?@author?ppcc
?*
?*/
public?class?sortDemo?{
/**
?*?字符數組,字符串元素從它里面獲取
?*/
private?static?final?char[]?strBase={
'A',?'B',?'C',?'D',?'E',?'F',?'G',?'H',?'I',?
'J',?'K',?'L',?'M',?'N',?'O',?'P',?'Q',?'R',?
'S',?'T',?'U',?'V',?'W',?'X',?'Y',?'Z',?'0',?
'1',?'2',?'3',?'4',?'5',?'6',?'7',?'8',?'9',
};
/**
?*?字符串list長度
?*/
private?static?int?SIZE=10;
/**
?*?隨機字符串數組鏈表
?*/
private?ArrayList<String>?randomStr;
/**
?*?構造函數
?*/
public?sortDemo(){
//定義隨機字符串數組鏈表
randomStr=new?ArrayList<String>(SIZE);
//randomStr賦值
this.getStrList();
}
/**
?*??隨機產生一個長度在10以內的字符串
?*??@return?隨機產生的字符串
?*/
private?String?getOneStr(){
//定義可變的字符串
StringBuffer?oneStr=new?StringBuffer();
//定義隨機數
Random?random=new?Random();
//字符串長度
int?oneStrLen=(random.nextInt(9)+1);
//for循環產生一個長度在10以內的字符串
for(int?i=0;?i<oneStrLen;?i++){
//隨機產生下標
int?index=random.nextInt(strBase.length);
//將隨機獲取的字符追加到字符串中
oneStr.append(strBase[index]);
}
return?oneStr.toString();
}
/**
?*?給randomStr賦值
?*/
private?void?getStrList(){
//for循環在randomStr中添加是個字符串
for(int?i=0;?i<SIZE;?i++){
//定義字符串
String?str;
do{
//隨機場所的字符串賦給str
str=getOneStr();
}while(randomStr.contains(str));
//直到原數組鏈表中不存該字符串,將其添加到randomStr
randomStr.add(str);
//添加成功提示語句
System.out.println("添加第"+(i+1)+"字符串:"+str);
}
}
/**
?*?將字符串排序后比較前后區別
?*/
public?void?sortRandomStr(){
System.out.println("******************排序前*********************");
for(String?currStr?:?randomStr)
System.out.println("字符串:"+currStr);
//排序
Collections.sort(randomStr);
System.out.println("******************排序后*********************");
for(String?currStr?:?randomStr)
System.out.println("字符串:"+currStr);
}
/**
?*?主函數
?*?@param?args
?*/
public?static?void?main(String[]?args)?{
(new?sortDemo()).sortRandomStr();
}
}
2015-08-08
可以定義一個字符串
string a="qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789"
然后用char ch=test.charAt(0);來挑選字符的,可能會方便點