天天看点

Random和Math.random

Random

Random:产生随机数的类

构造方法:

  • Random();

    没有种子,使用的是默认种子。是当前时间的毫秒值。
  • Random(long seed);

    结出有效的种子,给定种子后,每次出现的随机数是相同的。

成员方法:

  • public int nextInt();

    返回的是int范围内的随机数
  • public int nextInt(int n);

    返回的是(0.n)范围内的随机数,生成的是(0,n)的开区间的数。
  • public double nextDouble();

    返回下一个伪随机数,它是取自此随机数生成器序列的、在 0.0 和 1.0 之间均匀分布的 double 值
public class RandomTest {
    public static void main(String[] args) {
        //创建对象
//      Random random = new Random();
        Random random = new Random();       
        for(int x=  ;x<;x++) {
            int num = random.nextInt()+;
            System.out.println(num);
        }   
    }
}
结果:                   
           
public class Demo02Random {
    public static void main(String[] args) {
        Random r = new Random();
        for (int i = ; i < ; i++) {
            System.out.print(r.nextDouble()+"  ");
        }

    }
}
结果:         
           

Math.random

public static double random();

返回带正号的double值,该值大于等于0.0且小于1.0,。返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。

public class MathDemo {

    public static void main(String[] args) {
        System.out.println("random:"+Math.random());

        System.out.println("random:"+((int) (Math.random()*)+));
    }
}
           

random:0.3166464832091951

random:74

实例:获取start和end之间的随机数:

public static int getRandom(int start , int end) {
    int number = (int)Math.random() * (end-start+)+start;
    return number;
}