App下載

Java實(shí)現(xiàn)在指定范圍內(nèi)生成隨機(jī)整數(shù)

猿友 2021-07-26 14:54:40 瀏覽數(shù) (9323)
反饋

在開發(fā)項(xiàng)目中可能會(huì)有這樣的一個(gè)需求,需要在指定的范圍內(nèi)隨機(jī)生成一個(gè)整數(shù)值,例如 RPG 游項(xiàng)目中,在創(chuàng)建角色后隨機(jī)生成的屬性。下面,我為大家介紹幾種在 Java 中實(shí)現(xiàn)在指定范圍內(nèi)隨機(jī)生成整數(shù)的方法。

1、Java.Math.random()

說到隨機(jī),很多人的腦海中都會(huì)蹦出 Math.random() 這個(gè)方法。但它不能直接生成一個(gè)整數(shù),而是生成一個(gè)[0.0, 1.0)之間的 double 類型的小數(shù),如下:

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();
    }

}

打印結(jié)果:

0.9567296616768681

class java.lang.Double

由此可知,該方法只能在[0.0,1.0)之間生成一個(gè)隨機(jī) double 類型的小數(shù)。那么如何利用 random 方法來實(shí)現(xiàn)生成指定范圍內(nèi)的隨機(jī)小數(shù)呢?

假設(shè)我們需要生成一個(gè)范圍在[1,10]之間的隨機(jī)整數(shù),具體思路如下。

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);
}

最后打印結(jié)果(多次結(jié)果):

 9

10

1

10

3

1

6

8

7

5

可見結(jié)果符合我們的要求。

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

Random random=new Random();
int a=random.nextInt(25); //  在[0, 25)之間隨機(jī)生成一個(gè) int 類型整數(shù)

假設(shè)我們需要生成一個(gè) [63, 99]之間的整數(shù),具體實(shí)現(xiàn)思路如下:

[63, 99] ===> 先找到這兩個(gè)數(shù)的最大公倍數(shù) ===> 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);
        }

打印結(jié)果:

72

81

99

90

63

99

63

72

81

99

總結(jié)

以上就是關(guān)于使用 Java Math類中的 random 方法以及 Random 類中的 nextInt 方法實(shí)現(xiàn)在指定范圍內(nèi)隨機(jī)生成一個(gè)整數(shù)的詳細(xì)內(nèi)容,想要了解更多關(guān)于 Java 隨機(jī)數(shù)的應(yīng)用內(nèi)容,請(qǐng)關(guān)注W3Cschool!


0 人點(diǎn)贊