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

Java入门第三季第6章 Java 中的集合框架(下) 6-5 课后作业答案

至繁归于至简_
关注TA
已关注
手记 6
粉丝 7
获赞 27
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class Test {
    private static List<String> stringList;
    private static String finalString;

    public static void main(String[] args) {
        stringList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            do {
                createString();
            } while (stringList.contains(finalString));
            stringList.add(finalString);
        }

        System.out.println("————————————————————————排序前——————————————————————————");
        listOut(stringList);
        Collections.sort(stringList);
        System.out.println("————————————————————————排序后——————————————————————————");
        listOut(stringList);
    }

    private static void createString() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        int length = random.nextInt(10)+1;
        for (int i = 0; i < length; i++) {
            int type = random.nextInt(3);
            switch (type) {
            case 0:
                int[] num = {
                    0,1,2,3,4,5,6,7,8,9,    
                };
                sb.append(num[random.nextInt(10)]);
                break;

            case 1:
                char[] capital = {
                    'Q','W','E','R','T','U','I','O','P','A','S',
                    'D','F','G','H','J','K','L','Z','X','C','V',
                    'B','N','M','Y'
                };
                sb.append(capital[random.nextInt(26)]);
                break;

            case 2:
                char[] lowercase = {
                    'q','w','e','r','t','y','u','i','o','p',    
                    'a','s','d','f','g','h','j','k','l','z',    
                    'x','c','v','b','n','m'
                };
                sb.append(lowercase[random.nextInt(26)]);
                break;

            default:
                break;
            }
        }

        finalString = sb.toString();

    }

    private static void listOut(List<String> stringList) {
        for (String string : stringList) {
            System.out.println("元素:"+string);
        }
    }

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