javaRandom類的經常使用方法

Random類的構造方法:java

public Random();//該構造方法使用一個和當前系統時間對應的相對時間有關的數字做爲種子數dom

public Random(long seed);//經過制定一個種子數進行建立ide



方法:spa

public boolean nextBoolean();it

public double nextDouble();//生成隨機的double值,介於[0,1.0)class

public int nextInt();//介於int區間-231-231-1import

public int nextInt(int n);//[0,n)隨機數

Public void setSeed(long seed);程序

Random r=new Random();方法

double d1=r.nextDouble();

double d2=r.nextDouble()*5;//[0,5.0)就是將該區間擴大5倍

double d3=r.nextDouble()*1.5+1;//[1,2.5)先是生成[0,1.5)區間的隨機數字在加1便可

int n1=nextInt();//生成任意整數

int n2=r.nextInt(10);//[0,10)

n2=Math.abs(r.nextInt()%10);//[0,10)


int n2=r.nextInt(n);//[0,n)

n2=Math.abs(r.nextInt()%n);

int n3=r.nextInt(11);//[0,10]

n3=Math.abs(r.nextInt()%11);//[0,10]

int n4=r.nextInt(18)-3;//[-3,15)

n4=Math.abs(r.nextInt()%18)-3;

下面的java程序演示了一些基本的操做:

package nemo;

import java.util.*;

public class lala {

public static void main(String[]args)

{

Random r=new Random();

int n2=r.nextInt(10);//[0,10)

int n3=r.nextInt(11);//[0,10]

int n1=r.nextInt(18)-2;//[-2,16)

System.out.println(n2+" "+n3+" "+n1);

boolean b1=r.nextBoolean();

boolean b2=r.nextBoolean();

System.out.println(b1+" "+b2);

double d1=r.nextDouble();//[0,1.0)

double d2=r.nextDouble()*5;//[0,5.0)

double d3=r.nextDouble()*1.5+1;//[1,2.5)

System.out.println(d1+" "+d2+" "+d3);


}

}

相關文章
相關標籤/搜索