課后習(xí)題
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class SortTest {
private List<String> stringList = new ArrayList<String>();
/**
* 對隨機(jī)生成的十條字符串集合進(jìn)行排序 該字符串有如下要求:
* 1、字符串的長度為10以為的隨機(jī)整數(shù)
* ?2、字符串的每個字符都是隨機(jī)生成的的,可以重復(fù)
* 3、每條字符串不可重復(fù)
*
*/
public void testSort() {
// 定義一個random類來生成隨機(jī)數(shù)
Random random = new Random();
for (int i = 0; i < 10; i++) {
int stringLength = 0;// 獲取隨機(jī)長度
int temp = 0;// 接受隨機(jī)字符并轉(zhuǎn)換成字母
// 創(chuàng)建一個緩沖器,用于得到一個隨機(jī)字符串
StringBuffer buffer = new StringBuffer();
// 獲得10以內(nèi)的字符串長度
do {
stringLength = random.nextInt(10);
} while (stringLength == 0); // 長度不能為0
// 開始為buffer添加字符
do{
for (int j = 0; j < stringLength; j++) {
/*
* 用ascII碼進(jìn)行轉(zhuǎn)換成A~z的字符(65~90,97~112),獲取到一個字母后,添加給buffer
*/
do {
temp = random.nextInt(113);
} while (!((temp >= 65 && temp <= 90) || (temp >= 97 && temp <= 112)));
buffer.append((char) temp);
}
}while(stringList.contains(buffer.toString())); // do-while防止重復(fù)添加
// 若不重復(fù),添加到集合中
stringList.add(buffer.toString());
}
System.out.println("---------排序前----------");
print();
Collections.sort(stringList);
System.out.println("---------排序后----------");
print();
}
// 遍歷打印字符串集合
public void print() {
for (String str : stringList) {
System.out.println(str);
}
}
public static void main(String[] args) {
SortTest st = new SortTest();
st.testSort();
}
}
2016-01-10
good