在开发项目中可能会有这样的一个需求,需要在指定的范围内随机生成一个整数值,例如 RPG 游项目中,在创建角色后随机生成的属性。下面,我为大家介绍几种在 Java 中实现在指定范围内随机生成整数的方法。

1、Java.Math.random()

说到随机,很多人的脑海中都会蹦出 Math.random() 这个方法。但它不能直接生成一个整数,而是生成一个[0.0, 1.0)之间的 double 类型的小数,如下:

public class demo01 {

    public static void main(String[] args) {

        System.out.println(Math.random());
        System.out.println(getType(Math.random()));


    }

    public static String getType(Object obj){
        return obj.getClass().toString();
    }

}

打印结果:

0.9567296616768681

class java.lang.Double

由此可知,该方法只能在[0.0,1.0)之间生成一个随机 double 类型的小数。那么如何利用 random 方法来实现生成指定范围内的随机小数呢?

假设我们需要生成一个范围在[1,10]之间的随机整数,具体思路如下。

Math.random()  ===> [0.0, 1.0)
Math.random() * 10 ===> [0.0, 10.0)
(int)(Math.random() * 10 ) ===> [0, 9]
(int)(Math.random() *10) + 1 ===> [1, 10]
for (int i = 0; i < 10; i++) {
    int a=(int)(Math.random() * 10 )+1;
    System.out.println(a);
}

最后打印结果(多次结果):

 9

10

1

10

3

1

6

8

7

5

可见结果符合我们的要求。

2.Java.util.Random.nextInt();

Random random=new Random();
int a=random.nextInt(25); //  在[0, 25)之间随机生成一个 int 类型整数

假设我们需要生成一个 [63, 99]之间的整数,具体实现思路如下:

[63, 99] ===> 先找到这两个数的最大公倍数 ===> 9
[7, 11] * 9 ===> 将最小值取0
([0, 4] + 7) * 9
        Random random=new Random();
        for (int i = 0; i < 10; i++) {
            int a=(random.nextInt(5)+7)*9;
            System.out.println(a);
        }

打印结果:

72

81

99

90

63

99

63

72

81

99

总结

以上就是关于使用 Java Math类中的 random 方法以及 Random 类中的 nextInt 方法实现在指定范围内随机生成一个整数的详细内容,想要了解更多关于 Java 随机数的应用内容,请关注W3Cschool

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。