Java Random類的使用

2021-08-21 21:48:00 字數 2886 閱讀 8527

常見用法:

random類中的方法比較簡單,每個方法的功能也很容易理解。需要說明的是,random類中各方法生成的隨機數字都是均勻分布的,也就是說區間內部的數字生成的機率是均等的。下面對這些方法做一下基本的介紹:

a、public boolean nextboolean():是生成乙個隨機的boolean值,生成true和false的值機率相等,也就是都是50%的機率。

b、public double nextdouble():是生成乙個隨機的double值,數值介於[0,1.0)之間。

c、public int nextint():是生成在-2^31到2^31-1之間int值。如果需要生成指定區間的int值,則需要進行一定的數學變換,具體可以參看下面的使用示例中的**。

d、public int nextint(int n):是生成乙個介於[0,n)的區間int值,包含0而不包含n。如果想生成指定區間int值,也需要進行一定的數學變換,具體參看下面的使用示例中的**。

e、public void setseed(long seed):是重新設定random物件中的種子數。設定完種子數以後的random物件和相同種子數使用new關鍵字建立出的random物件相同。

f、 public float nextfloat(int n):返回下乙個偽隨機數,它是取自此隨機數生成器序列的、在0.01.0之間均勻分布的  float 值。

g、 public long nextlong():返回下乙個偽隨機數,它是取自此隨機數生成器序列的均勻分布的 long 值。

h、public double nextgaussian():返回下乙個偽隨機數,它是取自此隨機數生成器序列的、呈高斯(「正態」)分布的 double 值,其平均值是 0.0,標準差是 1.0。

1.產生int型別範圍內 -2147483648~2147483647 的隨機整數

random random=new random();

int a=random.nextint();

system.out.println(a);

2.產生[0,n)區間的隨機數,包含0但不包含n。

random random=new random();

int a=random.nextint(10); //產生0到10之間的隨機整數

system.out.println(a);

3.產生(0,1)範圍的隨機小數

random random=new random();

double a=random.nextdouble(); //產生0到1之間的隨機小數,預設double精度

bigdecimal bg = new bigdecimal(a);

double b = bg.setscale(1, bigdecimal.round_half_up).doublevalue();//精確到小數點後一位

system.out.println(b);

4.seed 種子的使用

注意:相同種子輸出的結果相同,不同種子輸出結果不同

(1)相同種子

random random1 = new random(100);

system.out.println(random1.nextint());

system.out.println(random1.nextfloat());

system.out.println(random1.nextboolean());

random random2 = new random(100);

system.out.println(random2.nextint());

system.out.println(random2.nextfloat());

system.out.println(random2.nextboolean());

執行結果相同:.

-1193959466

0.7346627

false

-1193959466

0.7346627

false

(2)不同種子

random random1 = new random(system.currenttimemillis());

system.out.println(random1.nextint());

system.out.println(random1.nextfloat());

system.out.println(random1.nextboolean());

system.out.println();

random random2 = new random(system.currenttimemillis());

system.out.println(random2.nextint());

system.out.println(random2.nextfloat());

system.out.println(random2.nextboolean());

執行結果不同:

-1674565819

0.2528978

false

-1664947096

0.5270924

true

類和類的使用

class people name xiaoming 類屬性,類裡面的變數稱為屬性 age 18 私有屬性,別人知道後不會去動它,概念性問題 age 18 也是私有屬性,訪問會報錯 a people 例項化 print a.age 通過例項訪問類屬性,雖然是私有的,但是訪問還是可以列印,b peop...

類模板的使用 類模板使用總結

歸納以上的介紹,可以這樣宣告和使用類模板 先寫出乙個實際的類。將此類中準備改變的型別名 如int要改變為float或char 改用乙個自己指定的虛擬型別名 如上例中的t 在類宣告前面加入一行,格式為 templatetemplate class a 類體用類模板定義物件時用以下形式 類模板名 實際型...

類的使用,物件的使用

一 類的使用 class student school luffycity def eat self print yes defdrink self print drink 檢視print student.dict 增student.teacher gaohui print student.dict...