豆芽丶
2016-11-04 22:35
public class CollectionTest {
public void testString() {
String str = "QWERTYUIOPASDFGHJKLZXCVBNMqwerty" +
"uiopasdfghjklzxcvbnm1234567890";
List<String> stringList = new ArrayList<String>();
Random random = new Random();
Integer k;
String m;
for (int i = 0; i < 10; i++) {
String s = "";
do {
k = random.nextInt(10);
for (int j = 0; j < k; j++) {
//生成字符串str长度范围的随机数
int r = random.nextInt(str.length());
//取一个字符
m = str.substring(r, r + 1);
//这种写法不知道规不规范。。
s = s + m;
}
}
//有时候会生成空字符串所以我加了个条件
while (stringList.contains(s) || stringList.contains(""));
stringList.add(s);
}
System.out.println("---------排序前---------");
for (String string : stringList) {
System.out.println("生成的字符串为:" + string);
}
Collections.sort(stringList);
System.out.println("---------排序后---------");
for (String string : stringList) {
System.out.println("生成的字符串为:" + string);
}
}
public static void main(String[] args) {
CollectionTest ct = new CollectionTest();
ct.testString();
}
}
这个你参考一下吧
package Course1; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; public class TestCollections { /* * 创建List<String>,生成十个随机字符串放入其中 * 字符串长度为10以内的随机整数 * 每条字符串的每个字符都为随机生成的字符,字符可重复 * 每条字符串随机不可重复 */ public void testSort(){ List<String> list = new ArrayList<String>(); String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); for (int i = 0; i < 10; i++) { int l; StringBuffer sb = new StringBuffer(); do { l = random.nextInt(10); for (int j = 0; j < l; j++) { sb.append(base.charAt(random.nextInt(base.length()))); } } while (list.contains(sb) || l == 0); list.add(sb.toString()); System.out.println("成功添加:" + sb); } System.out.println("***********排序前***********"); for(String str:list){ System.out.println(str); } Collections.sort(list); System.out.println("**********排序后**************"); for(String str:list){ System.out.println(str); } } public static void main(String[] args) { TestCollections tc=new TestCollections(); tc.testSort(); } }
你这个要是要随机加入了空字符串,do-while就会陷入死循环
Java入门第三季
409792 学习 · 4340 问题
相似问题