天天看點

JAVA擷取随機數——

        在Java中我們可以使用java.util.Random類來産生一個随機數發生器。它有兩種形式的構造函數,分别是Random()和Random(long seed)。Random()使用目前時間即System.currentTimeMillis()作為發生器的種子,Random(long seed)使用指定的seed作為發生器的種子。

        随機數發生器(Random)對象産生以後,通過調用不同的method:nextInt()、nextLong()、nextFloat()、nextDouble()等獲得不同類型随機數。

       1>生成随機數

           Random random = new Random();

           Random random = new Random(100);//指定種子數100

           random調用不同的方法,獲得随機數。

           如果2個Random對象使用相同的種子(比如都是100),并且以相同的順序調用相同的函數,那它們傳回值完全相同。如下面代碼中兩個Random對象的輸出完全相同

          import java.util.*;

          class TestRandom {

                public static void main(String[] args) {

                     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());

                }

            }

        2>指定範圍内的随機數

             随機數控制在某個範圍内,使用模數運算符%

            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使擷取資料範圍為非負數

       3>擷取指定範圍内的不重複随機數

            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]);

                  }

               }

            }