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

随机字符串的生成与排序

慕粉1617316290
关注TA
已关注
手记 5
粉丝 5
获赞 2

package ioomc.collection;
/**

  • 导入程序所需要的Java包
    */
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import java.util.Random;

public class CollectionsTest {
/**

  • 测试对字符串列表的排序
  • 列表中的字符串是随机产生的,长度在10以内的字符串
  • 分别输出排序前后的列表
  • Random类是用来产生随机的数或者其他的一些数据
    */
    public void testSorts(){
    List<String> stringList = new ArrayList<String>();
    String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
    Random random = new Random();
    int length;

/**

  • 产生10个10以内的随机数依次存放在length中,用来随机地给出10个随机字符串的长度
    */
    for(int i=0; i<10; i++){
    String string = new String();

    do{
        length = random.nextInt(10);
    }while(length == 0 );
    
    do{
        for(int j=0; j<length ; j++){
            string = string+alphabet.charAt(random.nextInt(62));
        }
    }while(stringList.contains(string));
    stringList.add(string);
    System.out.println("添加了字符串:"+string);

    }
    System.out.println("**排序前**");
    for (String string : stringList) {
    System.out.println("元素:"+string);
    }
    Collections.sort(stringList);
    System.out.println("排序后");
    for (String string : stringList) {
    System.out.println("元素:"+"'"+string+"'");
    }
    }
    public static void main(String[] args){
    CollectionsTest ct = new CollectionsTest();
    ct.testSorts();
    }
    }

测试结果:
添加了字符串:OWyfpg6
添加了字符串:isOSbS705
添加了字符串:Cd43
添加了字符串:Rb22k
添加了字符串:2te4
添加了字符串:pCuz0Gg9
添加了字符串:x53
添加了字符串:O9u
添加了字符串:9oKRz1ul
添加了字符串:8M9d6m118
**排序前**
元素:OWyfpg6
元素:isOSbS705
元素:Cd43
元素:Rb22k
元素:2te4
元素:pCuz0Gg9
元素:x53
元素:O9u
元素:9oKRz1ul
元素:8M9d6m118
排序后
元素:'2te4'
元素:'8M9d6m118'
元素:'9oKRz1ul'
元素:'Cd43'
元素:'O9u'
元素:'OWyfpg6'
元素:'Rb22k'
元素:'isOSbS705'
元素:'pCuz0Gg9'
元素:'x53'

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

热门评论

do{
length = random.nextInt(10);
}
while(length == 0 );
个人感觉这个循环没必要,想要排除掉0而已
length = random.nextInt(10)+1;

括号里的(10)表示从0-9取值,取到什么都+1就排除0了

但是题目是要字符串长度在10以内,说明不包括10,括号里写成9就好了;
 length = random.nextInt(9)+1;

这样length的值就是1-9中的任意整数了

而且做这个题应该是用StringBuilder来存储新生成的字符串比较好!!

查看全部评论