继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

随机长度字符串排序输出

青花瓷具
关注TA
已关注
手记 1
粉丝 1
获赞 5

package com.imooc.collection;

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

public class CollectionsTest {

//创建一个List
public List<String> rd = new ArrayList<String>();

/**
 * 创建一个能随机生成10个长度在10以内的字符串,然后通过collections.sort()进行排序并输出
 * @param args
 */
public void testRandom() {
    Random random = new Random();
    String str ="01234ABCmopqDEFGnKNO579PQRSTUVW6XYZabcdHIJefghijklrstLMwx8yz";

    for (int i = 0; i < 10; i++) {
        StringBuffer kString = new StringBuffer();

        int n = random.nextInt(10);
        for (int j = 0; j <= n; j++) {
            int startId = random.nextInt(str.length());
            kString.insert(j, str.charAt(startId)) ;
        }
        rd.add(kString.toString());
    }
}

/**
 * 遍历显示随机字符串
 * @param args
 */
public void testForEach(){
    for (String string : rd) {
        System.out.println("元素:"+string);
    }
}

/**
 * 用collections。sort()排序
 * @param args
 */
public void testCollectionsSort(){
    System.out.println("---------排序后的结果-----------");
    Collections.sort(rd);
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    CollectionsTest ct = new CollectionsTest();
    ct.testRandom();
    ct.testForEach();
    ct.testCollectionsSort();
    ct.testForEach();

}

}

打开App,阅读手记
4人推荐
发表评论
随时随地看视频慕课网APP

热门评论

是10以内的,这个不行

字符串长度为10,你这个错了

没有判断字符串是否重复吧?

查看全部评论