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

用java写的关于随机数的运用

长是人千离
关注TA
已关注
手记 5
粉丝 5
获赞 21
package test;

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

public class CollectionsTest {
    public void testSort1() {
        List<Integer> integerList = new ArrayList<Integer>();
        Random random = new Random();
        Integer k;
        for (int i = 0; i < 10; i++) {
            do {
                k = random.nextInt(100);
            } while (integerList.contains(k));
            integerList.add(k);
            System.out.println("成功");
        }
        System.out.println("排序前");
        for (Integer integer : integerList) {
            System.out.print(integer + " ");
        }
        Collections.sort(integerList);
        System.out.println("排序后");
        for (Integer integer : integerList) {
            System.out.print(integer + " ");
        }
    }

    public void TestSort2() {
        List<String> stringList = new ArrayList<String>();
        String a = "";
        int k; //字的个数
        int charnum; //字符串中字符的个数
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            do {
                charnum = random.nextInt(10);
                a = "";
                for (int j = 0; j < charnum; j++) {
                    k = random.nextInt(123);
                    if ((k >= 48 && k <= 57) 

                            (k >= 65 && k <= 90) 

                            (k >= 97 && k <= 122)) {

                        a = a+(char) k;
                    }
                }
            } while (stringList.contains(a));
            stringList.add(a);
            System.out.println("添加成功");
        }
        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.TestSort2();
    }
}
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP