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

 
    


 
   

你可能感兴趣的:(java)