生成随机字符串,欢迎指教
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | package com.imooc; import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class CollectionSort { ArrayList<String> RandomList = new ArrayList<String>(); /** * 向ArrayList中添加字符串 */ public void addList() { String str; for ( int i = 0 ; i < 10 ; i++) { do { str = getString(); } while (RandomList.contains(str)); RandomList.add(str); System.out.println( "成功添加:" +str); } } /** * 排序 */ public void sortCollection() { System.out.println( "--------排序前--------" ); for (String string : RandomList) { System.out.println( "随机数列:" +string); } System.out.println( "--------排序后--------" ); Collections.sort(RandomList); for (String string : RandomList) { System.out.println( "随机数列:" +string); } } /** * 生成长度10以内的随机字符串 * @return */ public String getString() { Random random = new Random(); String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST" ; StringBuilder sb = new StringBuilder(); int length = str.length(); do { int ran = random.nextInt(length); sb.append(str.charAt(ran)); } while (sb.length() < random.nextInt( 10 )); return sb.toString(); } //生成3个1000以内的不重复的数字 public void third(){ int i = 1 ; Random random = new Random(); int [] id = new int [ 3 ]; id[ 0 ]=random.nextInt( 1000 ); while (i< 3 ){ if (id[i] != random.nextInt( 1000 )){ id[i] = random.nextInt( 1000 ); } else { continue ; } i++; } for ( int j : id) { System.out.println(j); } } public static void main(String[] args) { CollectionSort cs = new CollectionSort(); cs.addList(); cs.sortCollection(); // cs.third(); } } |