Java基础算法练习

一、需求:
    编写一个程序,获取10个1-20之间的随机数,要求随机数不能重复,并在控制台输出
    思路:
    1:创建Set集合对象
    2:创建随机数对象
    3:判断集合的长度是不是小于10
        是:产生一个随机数,添加到集合
        回到3继续
    4:遍历集合

了解的类及其函数:Math类和Random类

(1)Math类

Math.random()方法:Math.random()是令系统随机选取大于等于 0.0 且小于 1.0 的伪随机 double 值

产生一个[0,1)之间的随机数:Math.random();

1.随机生成a~z之间的字符

(char)('a'+Math.random()*('z'-'a'+1));

2.随机生成cha1~cha2的字符

(char)(cha1+Math.random()*(cha2-cha1+1));

产生一个[1,20)之间的随机数:Math.random()*19+1;


//        Set<Integer> s = new HashSet<Integer>();
        Set<Integer> s = new TreeSet<Integer>();

        for (int i = 0; s.size() < 10; i++) {
            int num = (int) (Math.random() * 19) + 1;
            s.add(num);
        }
        for (Integer k : s) {
            System.out.println(k);
        }

随机生成字符

1.随机生成a~z之间的字符

(char)('a'+Math.random()*('z'-'a'+1));

2.随机生成cha1~cha2的字符

(char)(cha1+Math.random()*(cha2-cha1+1));

(2)Random类:通过实例化一个Random对象创建一个随机数生成器。

Random r = new Random();

r.nextInt(n);该方法的作用是生成一个随机的int值,该值介于[0,n)的区间,也就是0到n之间的随机int值,包含0而不包含n。

产生一个[1,20)之间的随机数:r.nextInt(20)+1

//Set<Integer> s = new HashSet<Integer>();
        Set<Integer> s = new TreeSet<Integer>();

        Random r = new Random();

        while (s.size() < 10) {
            int number = r.nextInt(20) + 1;
            s.add(number);
        }

        for (Integer k : s) {
            System.out.println(k);
        }

Random类中还提供各种类型随机数的方法:
nextInt():返回一个随机整数(int)
nextInt(int n):返回大于等于0、小于n的随机整数(int)
nextLong():返回一个随机长整型值(long)
nextBoolean():返回一个随机布尔型值(boolean)
nextFloat():返回一个随机浮点型值(float)
nextDouble():返回一个随机双精度型值(double)
nextGaussian():概率密度为高斯分布的双精度值(double)

Guess you like

Origin blog.csdn.net/Januea/article/details/120862012