手记

随机产生十个随机长度的字符串,并排序

package com.imooc.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;

public class randomString{
    public static void main(String[] args){
            ArrayList<String> stringList = new ArrayList<String>();
            String string = "0123456789qwerrtyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
            Random random = new Random();
            int k = random.nextInt(string.length());

            for(int i = 0 ; i < 10 ; i++){    
                StringBuffer buffer = new StringBuffer();
                    do{
                            int num = random.nextInt(10) + 1;    //产生10以内的整数用来表示字符串长度
                            for(int j = 0 ; j < num ; j++){
                                    char c = string.charAt(random.nextInt(k));
//                                  System.out.println("产生的随机字符为:" + c);
                                    buffer.append(c);
                            }
                            System.out.println("第" + i + "个字符串为:" + buffer);
                    }while(stringList.contains(buffer) && buffer.equals(""));
                    String temp = buffer.toString();
                    stringList.add(temp);
                    buffer = null;
            }

        System.out.println("-------排序前-------");
        for(String str:stringList){
            System.out.println("元素:"+str);
        } 

        Collections.sort(stringList);

        System.out.println("-------排序后-------");
        for(String str:stringList){ 
            System.out.println("元素:"+str);
        }
    }
}
0人推荐
随时随地看视频
慕课网APP