手记

第六章 生成随机字符串并排序 练习

package com.imooc;

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

import java.util.List;
import java.util.Random;

public class TestRandom {
public static List<String> randomstring=new ArrayList<String>();
public static void testRandomString(){
Random random=new Random();
String str="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm1234567890";
for(int i=0;i<10;i++){
StringBuilder sb=new StringBuilder();
int length;
do{
length=random.nextInt(11);

            for(int j=0;j<length;j++){
                sb=sb.append(str.charAt(random.nextInt(61)));
            }
        }while(length==0randomstring.contains(sb));
        randomstring.add(sb.toString());
    }
}

public static void main(String[] args) {
    TestRandom.testRandomString();
    System.out.println("--------未排序前的字符串--------");
    for (String str : randomstring) {

        System.out.println(str);
    }
    Collections.sort(randomstring);
    System.out.println("--------排序后的字符串--------");
    for (String str : randomstring) {

        System.out.println(str);
    }
}

}

0人推荐
随时随地看视频
慕课网APP