qq_慕码人5248226
2019-07-22 18:20
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Created by DELL on 2019/7/22. */ public class CollectionsTest1 { public void testSort() { List<String> list = new ArrayList<>(); Random random = new Random(); String s =new String(); for (int i = 0; i < 10; i++) { do { int w = s.length(); Integer k = random.nextInt(10); w = k; s = randomString(w); } while (list.contains(s)); list.add(s); } System.out.println("----------排序前------------"); for (String string : list) { System.out.println("随机字符串:" + string); } Collections.sort(list); System.out.println("-------排序后-------"); for (String string : list) { System.out.println("随机字符" + string); } } public String randomString(int sun) { String s = ""; Random r = new Random(); for (int j = 0; j < 10; j++) { s = s + (char) Math.abs(r.nextInt(26) % 26 + 96); } return s; } public static void main(String[] ages) { CollectionsTest1 st = new CollectionsTest1(); st.testSort(); } }
你写的有点错误,我写了下
public void testSort3()
{
List<String> listString = new ArrayList<String>();
Random r1 = new Random();
String s = new String();
for(int i=0;i<10;i++)
{
do {
Integer k = r1.nextInt(10);
s = randomString(k);
} while (listString.contains(s));
listString.add(s);
}
System.out.println("—————————输出排序前———————————————");
for(int i=0;i<listString.size();i++)
{
String s2 = (String)listString.get(i);
System.out.println("元素:"+s2);
}
Collections.sort(listString);
System.out.println("————————————输出排序后————————————————————");
for(String s3:listString)
{
System.out.println("元素:"+s3);
}
}
public String randomString(int k)
{
String s1 = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFG"
+ "HIJKLMNOPQRSTUVWXYZ";
String s = "";
Random random = new Random();
for(int j=0;j<k;j++)
{
int index = random.nextInt(62);
s=s+s1.charAt(index);
}
return s;
}
你的问题在哪里,想要别人指点啥?
Java入门第三季
409792 学习 · 4340 问题
相似问题