這是我寫的課后習題代碼,供同學們參考
public void sortRandomString(){
List<String> stringList = new ArrayList<String>();
String str;
for(int i=0;i<10;i++){
//隨機生成數字或字母并添加到str
do{
str="";
for (int x = 0; x < 10; x++) {
int j = (int) (Math.random() * 3 + 1);
switch (j) {
case 1:
// 生成隨機數字
int k = (int) (Math.random() * 10);
str += k;
break;
case 2:
// 生成隨機大寫字母
int m = (int) (65 + Math.random() * 26);
str += (char) m;
break;
case 3:
// 生成隨機小寫字母
int n = (int) (97 + Math.random() * 26);
str += (char) n;
break;
}
if(Math.random()<0.1)
break;
}
}while(stringList.contains(str));
stringList.add(str);
System.out.println("List中添加了字符串:"+str);
}
System.out.println("----------------List排序前-----------------");
for (String string : stringList) {
System.out.println(("元素:"+string));
}
Collections.sort(stringList);
System.out.println("----------------List排序后-----------------");
for (String string : stringList) {
System.out.println(("元素:"+string));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CollectionsTest ct = new CollectionsTest();
ct.sortRandomString();
}
}
2015-08-28
蓋蓋蓋