手记

Java入门第三季6-5随机String作业代码

package collectiontest;

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

public class CollectionsTest {

public static void main(String[] args) {
    CollectionsTest clt = new CollectionsTest();
    //clt.testSort1();
    clt.testSort2();

}

public void testSort1() {
    List<Integer> lt = new ArrayList<Integer>();
    Random rd = new Random();

    Integer k;
    for (int i = 0; i < 10; i++) {
        do {
            k = rd.nextInt(100);
        } while (lt.contains(k));// 为了保证不重复
        lt.add(k);
        System.out.println("成功添加整数" + k);
    }
    System.out.println("--------排序前-----------");
    for (Integer i : lt) {
        System.out.println("元素" + i);
    }
    Collections.sort(lt);
    System.out.println("--------排序后-----------");
    for (Integer i : lt) {
        System.out.println("元素" + i);
    }

}

public void testSort2() {
    List<String> ltString = new ArrayList<String>();
    Random rd = new Random();
    StringBuffer st;
    String randomString="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    for (int i = 0; i < 10; i++) {
        do {
            int length=rd.nextInt(10);
            st = new StringBuffer(length);

            for (int j = 0; j < length; j++) {

                char temp=randomString.charAt(rd.nextInt(randomString.length()));

                st.append(temp);

            }

        } while (ltString.contains(st));
        ltString.add(st.toString());

    }
    for(int i=0;i<ltString.size();i++){
        System.out.println("数组"+ltString.get(i));
    }

    System.out.println("--------排序前-----------");
    for (String s : ltString) {
        System.out.println("元素" + s);
    }
    Collections.sort(ltString);
    System.out.println("--------排序后-----------");
    for (String s : ltString) {
        System.out.println("元素" + s);
    }
}

}

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

热门评论

System.out.println("666");

查看全部评论