火星葱
2015-09-23 17:42
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class sortList {
Random random=new Random();
String randomString;
StringBuffer string=new StringBuffer();
//将随机生成的字符串randomString插入stringList
public void testSort(){
List<String> stringList=new ArrayList<String>();
for(int i=0;i<10;i++){
do {
randomString=getString();
} while (stringList.contains(randomString));
stringList.add(randomString);
System.out.println("成功添加字符串:"+getString());
}
System.out.println("-------------排序前--------------");
for(String strings:stringList){
System.out.println("元素:" + strings);
}
Collections.sort(stringList);
System.out.println("----------------排序后-------------------");
for(String strings:stringList){
System.out.println("元素:" + strings);
}
}
//生成随机字符串,赋值给randomString
public String getString(){
String base="abcdefghijklmnopqrstuvwxyz0123456789";
int k =random.nextInt(10);
for (int i = 0; i < k; i++) {
int f =random.nextInt(base.length());
string.append(base.charAt(f));
}
randomString=string.toString();
System.out.println("随机生成字符串:"+randomString);
return randomString;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
sortList s=new sortList();
//s.getString();
s.testSort();
}
}
代码有两处错误,改正即可:
1:testSort()里面的 System.out.println("成功添加字符串:"+getString()); 将getString改为randomString
2:getString里面需要将string清空,可用string.delete(0, string.length());语句.放在randomString=string.toString();后面即可.不然string会越来越长.也可将StringBuffer string=new StringBuffer();放在getString方法里定义,局部变量会自动删除;
3:int k =random.nextInt(10); 改为int k =random.nextInt(10)+1;(看个人理解吧,因为k为零没有意义);
记得点赞!!!
base串中加入26个大写字母。
Java入门第三季
409792 学习 · 4340 问题
相似问题