1. 程式人生 > >Random的nextInt用法

Random的nextInt用法

因為想當然的認為Random類中nextInt()(注:不帶引數),會產生偽隨機的正整數,採用如下的方式生成0~99之間的隨機數:

	Random random = new Random();
    	System.out.println(random.nextInt() % 100);
但是在執行的時候,發現上面的方法有時會產生負數,通過檢視Random類的原始碼才發現,不帶引數的nextInt會產生所有有效的整數,所以當然會有負數產生了。

正確的解法應該是:

	Random random1 = new Random();
	System.out.println(random1.nextInt(100)); //100是不包含在內的,只產生0~99之間的數。
應用:

生成亂序不重複陣列

package com.cn.wuliu.utils;
import java.util.Random;


public class Arith {
      //對給定數目的自0開始步長為1的數字序列進行不重複亂序
      public static int[] getSequence(int maxnum) {
          int[] sequence = new int[maxnum];
          for(int i = 0; i < maxnum; i++){
              sequence[i] = i;
          }
//         System.out.println(Arrays.toString(sequence));
//		[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
          Random random = new Random();
          for(int i = 0; i < maxnum; i++){
              int p = random.nextInt(maxnum);
              int tmp = sequence[i];
              sequence[i] = sequence[p];
              sequence[p] = tmp;
          }
          random = null;
          return sequence;
      } 

	//對給定數目的自minnum開始步長為1到maxnum的數字序列進行不重複亂序
	public static int[] getSequence(int minnum,int maxnum) {
    	  int num = maxnum - minnum + 1;
          int[] sequence = new int[num];
          for(int i = 0; i < num; i++){
              sequence[i] = i + minnum;
          }
//          System.out.println(Arrays.toString(sequence));
          Random random = new Random();
          for(int i = 0; i < num; i++){
              int p = random.nextInt(num);
              int tmp = sequence[i];
              sequence[i] = sequence[p];
              sequence[p] = tmp;
          }
          random = null;
          return sequence;
      } 


      public static void main(String[] agrs){
    	  Arith arith = new Arith();
    	  int[] i = arith.getSequence(10);
    	  for(int n=0;n<i.length;n++){
    		  System.out.print(i[n]);
    	  }
    	  System.out.println();
    	  int[] j = arith.getSequence(3,8);
    	  for(int n=0;n<j.length;n++){
    		  System.out.print(j[n]);
    	  }
      }
}