天天看點

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