1. 程式人生 > >Java 如何獲得指定區間的數

Java 如何獲得指定區間的數

Java實用工具類庫中的類java.util.Random提供了產生各種型別隨機數的方法。它可以產生int、long、float、double以 及Goussian等型別的隨機數。這也是它與java.lang.Math中的方法Random()最大的不同之處,後者只產生double型的隨機 數。
類Random中的方法十分簡單,它只有兩個構造方法和六個普通方法。
構造方法:
(1)public Random()
(2)public Random(long seed)

Random()使用當前時間即System.currentTimeMillis()作為發生器的種子,Random(long seed)使用指定的seed作為發生器的種子。
Java產生隨機數需要有一個基值seed,在第一種方法中基值預設,則將系統時間作為seed。
普通方法:
(1)public synonronized void setSeed(long seed)
該方法是設定基值seed。
(2)public int nextInt()
該方法是產生一個整型隨機數。
(3)public long nextLong()
該方法是產生一個long型隨機數。
(4)public float nextFloat()
該方法是產生一個Float型隨機數。
(5)public double nextDouble()
該方法是產生一個Double型隨機數。
(6)public synchronized double nextGoussian()
該方法是產生一個double型的Goussian隨機數。
如果2個Random物件使用相同的種子(比如都是100),並且以相同的順序呼叫相同的函式,那它們返回值完全相同。如下面程式碼中兩個Random物件的輸出完全相同
 指定範圍內的隨機數
  隨機數控制在某個範圍內,使用模數運算子%
             import java.util.*;
                  class TestRandom {
                       public static void main(String[] args) {
                            Random random = new Random();
                            for(int i = 0; i < 10;i++) {
                                System.out.println(Math.abs(random.nextInt())%10);
                            }
                       }
                  }
              獲得的隨機數有正有負的,用Math.abs使獲取資料範圍為非負數

獲取指定範圍內的不重複隨機數
             import java.util.*;
             class TestRandom {
                   public static void main(String[] args) {
                        int[] intRet = new int[6];
                        int intRd = 0; //存放隨機數
                        int count = 0; //記錄生成的隨機數個數
                        int flag = 0; //是否已經生成過標誌
                        while(count<6){
                             Random rdm = new Random(System.currentTimeMillis());
                             intRd = Math.abs(rdm.nextInt())%32+1;
                             for(int i=0;i<count;i++){
                                 if(intRet[i]==intRd){
                                     flag = 1;
                                     break;
                                 }else{
                                     flag = 0;
                                 }
                             }
                             if(flag==0){
                                 intRet[count] = intRd;
                                 count++;
                             }
                    }
                   for(int t=0;t<6;t++){
                       System.out.println(t+"->"+intRet[t]);
                   }
                }
             }


也可以有nextFloat等等,各種基本型別都有

Math.random也可以
比如說你想要0-10之間的隨機數
你可以這樣寫
(int)(Math.random()*10);

JAVA產生指定範圍的隨機數
產生Min-Max之間的數字

 Random random=new Random();
          int top = random.nextInt(maxtop)%(maxtop-mintop+1) + mintop;
   另一種實現原理:
      Math.round(Math.random()*(Max-Min)+Min)

long Temp; //不能設定為int,必須設定為long
//產生1000到9999的隨機數
Temp=Math.round(Math.random()*8999+1000);