// 方法一利用ASCII码:生成10个随机字符串,且长度不大于10,然后添加进List集合
public void testSort2() {
List<String> list = new ArrayList<>();
Random random = new Random();
int temp = 0;
for (int k = 0; k < 10; k++) {
int n;
do {
n = random.nextInt(11);
} while (n == 0);
String str = "";
for (int i = 0; i < n; i++) {
do {
temp = random.nextInt(123);
} while (temp < 48 || (temp > 57) && (temp < 65) || (temp > 90) && (temp < 97));
char ch = (char) temp;
str += ch;
}
list.add(str);
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
// Collections.sort(list);
// for (String str : list) {
// System.out.print(str + " ");
// }
}
// 方法二利用StringBuilder类:生成10个随机字符串,且长度不大于10,然后添加进List集合
public void testSort3() {
List<String> list = new ArrayList<>();
Random random = new Random();
String strList="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (int i = 0; i < 10; i++) {
StringBuilder str = new StringBuilder();
int n;
do {
n = random.nextInt(11);
} while (n == 0);
do {
for (int j = 0; j < n; j++) {
int temp = random.nextInt(62);
str.append(strList.charAt(temp));
}
} while (list.contains(str.toString()));
list.add(str.toString());
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
}
小白只看得懂第二种方法,大神活学活用,深感惭愧哎、小弟受教了。奈何脑容量太小(∩_∩)别说如答主运用自如了,知识点都还没整理过来!佩服佩服!
int n;
do {
n = random.nextInt(11);
} while (n == 0);
String str = "";
for (int i = 0; i < n; i++)
第一个方法 这一段的do-while 可以删掉 把or循环的int i=0 改成i=-1
看错了不好意思 == 我自己弄错
好像和老师的要求有一点偏差第二种方法
写的不错,这么基础的代码也没必要再继续优化了