为了账号安全,请及时绑定邮箱和手机立即绑定

JAVA入门第三季-随机字符串排序

标签:
Java
package com.imooc;

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

public class HelloWorld {
    public static void main(String[] args) {

        List<String> list=new ArrayList<String>();
        final int fixedSize=10;
        int count=0;
        while(count!=fixedSize){
            char[] strs=new char[10];
//          System.out.println(x+"th string:");
            Random rand=new Random();
            int length=rand.nextInt(10)+1;
//          System.out.println("length:"+length);
            for(int i =0; i<length; i++){
                int flag=rand.nextInt(3);
//              System.out.println("flag:"+flag);
                switch(flag)
                {
                    case 0://numbers
                        strs[i]=(char) ('0'+rand.nextInt(10));
//                      System.out.println(i+"th char is "+strs[i]);
                        break;
                    case 1://lowercase letters
                        strs[i]=(char) ('a'+rand.nextInt(26));
//                      System.out.println(i+"th char is "+strs[i]);
                        break;
                    case 2://Uppercase letters
                        strs[i]=(char) ('A'+rand.nextInt(26));
//                      System.out.println(i+"th char is "+strs[i]);
                        break;
                }
            }
            String toAdd=new String(strs);
//          System.out.println(toAdd);
//          System.out.println("--------------------------------------");
            if(list.contains(toAdd)){
                continue;
            }else{
                list.add(toAdd);
//              System.out.println("Successfully added string");
                count++;
            }
//          System.out.println(count);
//          do{
//              list.add(toAdd);
//          }while(!(list.contains(toAdd)));
        }

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

}
点击查看更多内容
4人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
0
获赞与收藏
12

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消