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

详细注释,Java入门第三季6-5的作业

标签:
Java
//定义一个String泛型的List并在构造函数中初始化它。
public class CollectionsTest {
    List<String>stringList;
    List<Student>studentList;

    public CollectionsTest(){
        this.stringList =new ArrayList<String>();
        this.studentList = new ArrayList<Student>();
    }
//在此方法内完成随机生成10条10以内长度的字符串,并重新排序。
public void testStringList(){
        Random rd = new Random();
        String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl"
                + "mnopqrstuvwxyz0123456789";//索引位置0~61。

        String sb2=null;//创建一个空字符串用来接收转换后的StringBuilder类型的字符串

        for(int i = 0;i<10;i++){//外层循环控制生成字符串的数量,题目是10条。
            do{
            StringBuilder sb = new StringBuilder();//定义一个内容可变的字符串用来接收charAt方法截取的每个字符。
            int m =rd.nextInt(10);//随机生成10以内的整数。
            for(int j = 0 ;j<=m;j++){//控制字符串的位数,题目是说10以内随机数。
                int n = rd.nextInt(61);//控制生成字符串的每一位。从s中随机截取。
                sb=sb.append(s.charAt(n));//用charAt截取s中的字符并添加到可变字符串sb中。
            }
            sb2 = sb.toString();//将StringBuilder类型的字符串转换为String类型的字符串,便于用contains方法。
            }while(stringList.contains(sb2));//判断生成的字符串是否重复。
            stringList.add(sb2);//将符合标准的字符串添加进List中。
        }

        System.out.println("排序前的stringList:");
        for(String string:stringList){//foreach遍历排序前的List。
            System.out.println(string);
        }
        Collections.sort(stringList);//用Collections.sort方法对List进行排序。
        System.out.println("--------------我是萌萌的分界线-----------");
        System.out.println("排序后的stringList:");
        for(String string:stringList){//用foreach遍历输出排序后的List。
            System.out.println(string);
        }
    }
//主函数。
public static void main(String[] args) {
        // TODO Auto-generated method stub
    CollectionsTest ct = new CollectionsTest();
    ct.testStringList();

//运行后的结果。
图片描述

点击查看更多内容
TA 点赞

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

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

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

举报

0/150
提交
取消