Java中的随机数

来自姬鸿昌的知识库
跳到导航 跳到搜索

Math.random()

public class Test {

    public static void main(String[] args) {

        double random = Math.random();

        System.out.println(random);

    }

}
0.8981455972172399

[0.0,1.0)

0.0 <= random < 1.0


生成大于等于 m 小于 n 的伪随机双精度浮点数

1 <= random < 5

public class Test1 {

    public static void main(String[] args) {

        int m = 1;
        int n = 5;

        double random = Math.random() * (n - m) + m;

        System.out.println(random);

    }

}
3.3551556765339487



Random类

上面提到的 Math.random() 也是通过调用 Random 类实现的

伪随机整数

import java.util.Random;

public class Test2 {
    public static void main(String[] args) {
        Random random = new Random();
        int nextInt = random.nextInt();
        System.out.printf("伪随机整数:%d\n", nextInt);
    }
}
伪随机整数:-240205213

限制最大值的伪随机非负整数

import java.util.Random;

public class Test3 {
    public static void main(String[] args) {
        int lt = 10;
        Random random = new Random();
        int nextInt = random.nextInt(lt);
        System.out.printf("得到的小于 %d 的非负伪随机整数是:%d\n", lt, nextInt);
    }
}
得到的小于 10 的非负伪随机整数是:6

获取其他随机值

import java.util.Random;

public class Test4 {

    public static void main(String[] args) {
        Random random = new Random();

        double nextDouble = random.nextDouble();
        System.out.println(nextDouble);
        System.out.printf("nextDouble:%f\n", nextDouble);

        long nextLong = random.nextLong();
        System.out.printf("nextLong:%d\n", nextLong);

        boolean nextBoolean = random.nextBoolean();
        System.out.printf("nextBoolean:%b\n", nextBoolean);

    }

}
0.6720388983690521
nextDouble:0.672039
nextLong:5729745496854116442
nextBoolean:true