Java第三季老师布置的作业:生成随机字符串并排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class TestRandomString {
/**
- 1、通过Collections.sort()方法,对String泛型的List进行排序;
- 2、创建一个String泛型的List,往其中添加十条随机字符串
- 3、每条字符串的长度为10以内的随机整数
- 3、每条字符串的每个字符都为随机生成的字符,字符可以重复
- 4、每条字符串不可重复
- 调用Collections.sort()方法对其进行排序
@param args
*/
public void testSort(){
List<String> stringlist=new ArrayList<String>();
char[] chars={‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘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’, ‘a’, ‘b’, ‘c’, ‘d’,
‘e’, ‘g’, ‘f’, ‘h’, ‘i’, ‘j’, ‘k’, ‘l’, ‘n’, ‘m’, ‘o’, ‘p’, ‘q’, ‘r’,
‘s’, ‘t’, ‘u’, ‘v’, ‘w’, ‘x’, ‘y’, ‘z’};
Random b=new Random();
int k;
for(int i=0;i<10;i++){
do{
k=b.nextInt(10); //随机生成10以内的整数,当k=0时重新生成
}while(k==0);
System.out.println(“k:”+k);
StringBuffer sb=new StringBuffer();
for(int j=1;j<=k;j++){
int m=b.nextInt(chars.length);
char n=chars[m];
sb.append(n);
}
stringlist.add(sb.toString());
String sp=sb.toString();
System.out.println(“添加了字符串:”+sp);
}
System.out.println(“————排序前—————-“);
for(String x:stringlist){
System.out.println(“元素:”+x);
}
Collections.sort(stringlist);
System.out.println(“————排序后—————-“);
for(String x:stringlist){
System.out.println(“元素:”+x);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stubTestRandomString trs=new TestRandomString(); trs.testSort();
}
}
相关文章