如何获取一个随机数

java.lang.Math类中的静态方法

double value = Math.random();
//value >= 0 && value < 1.0

公式:

[a,b] (int) (Math.random() * (b - a + 1) + a)

java.util.Random类

随机产生一个数,举例如下:

import java.util.Random;

public class RandomTest {
    public static void main(String[] args) {
        Random random = new Random();
        int num = random.nextInt();
        System.out.println(num);
        
       int i = random.nextInt(10);
        //返回的是0到指定值之间的int值,不包括指定值,包括
        System.out.println(i); //[0,10)

        int i1 = random.nextInt(19 - 10 + 1) + 10;
        System.out.println(i1); //[10,19] 
    }
}

总结:

如果要得到一个[0,x)之间的随机数,用nextInt(x);

如果要得到一个[0,x]之间的随机数,用nextInt(x + 1);

如果要得到一个[x,y]之间的随机数,用nextInt(y - x + 1) + x;

发布了37 篇原创文章 · 获赞 7 · 访问量 1595

猜你喜欢

转载自blog.csdn.net/weixin_43862596/article/details/105232378