Random的nextInt用法

来源:互联网 发布:淘宝改后台软件多少钱 编辑:程序博客网 时间:2024/05/21 16:03

Random的nextInt用法

原创 2017年05月12日 11:39:40


因为想当然的认为Random类中nextInt()(注:不带参数),会产生伪随机的正整数,采用如下的方式生成0~99之间的随机数:

[java] view plain copy
  1.   
[java] view plain copy
  1. Random random = new Random();  
  2.     System.out.println(random.nextInt() % 100);  

但是在运行的时候,发现上面的方法有时会产生负数,通过查看Random类的源代码才发现,不带参数的nextInt会产生所有有效的整数,所以当然会有负数产生了。

正确的解法应该是:

[java] view plain copy
  1.   
[java] view plain copy
  1. Random random1 = new Random();  
  2. System.out.println(random1.nextInt(100)); //100是不包含在内的,只产生0~99之间的数。  
应用:

生成乱序不重复数组

[java] view plain copy
  1.   
[java] view plain copy
  1. package com.cn.wuliu.utils;  
  2. import java.util.Random;  
  3.   
  4.   
  5. public class Arith {  
  6.       //对给定数目的自0开始步长为1的数字序列进行不重复乱序  
  7.       public static int[] getSequence(int maxnum) {  
  8.           int[] sequence = new int[maxnum];  
  9.           for(int i = 0; i < maxnum; i++){  
  10.               sequence[i] = i;  
  11.           }  
  12. //         System.out.println(Arrays.toString(sequence));  
  13. //      [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  
  14.           Random random = new Random();  
  15.           for(int i = 0; i < maxnum; i++){  
  16.               int p = random.nextInt(maxnum);  
  17.               int tmp = sequence[i];  
  18.               sequence[i] = sequence[p];  
  19.               sequence[p] = tmp;  
  20.           }  
  21.           random = null;  
  22.           return sequence;  
  23.       }   
  24.   
  25.     //对给定数目的自minnum开始步长为1到maxnum的数字序列进行不重复乱序  
  26.     public static int[] getSequence(int minnum,int maxnum) {  
  27.           int num = maxnum - minnum + 1;  
  28.           int[] sequence = new int[num];  
  29.           for(int i = 0; i < num; i++){  
  30.               sequence[i] = i + minnum;  
  31.           }  
  32. //          System.out.println(Arrays.toString(sequence));  
  33.           Random random = new Random();  
  34.           for(int i = 0; i < num; i++){  
  35.               int p = random.nextInt(num);  
  36.               int tmp = sequence[i];  
  37.               sequence[i] = sequence[p];  
  38.               sequence[p] = tmp;  
  39.           }  
  40.           random = null;  
  41.           return sequence;  
  42.       }   
  43.   
  44.   
  45.       public static void main(String[] agrs){  
  46.           Arith arith = new Arith();  
  47.           int[] i = arith.getSequence(10);  
  48.           for(int n=0;n<i.length;n++){  
  49.               System.out.print(i[n]);  
  50.           }  
  51.           System.out.println();  
  52.           int[] j = arith.getSequence(3,8);  
  53.           for(int n=0;n<j.length;n++){  
  54.               System.out.print(j[n]);  
  55.           }  
  56.       }  
  57. }  

[java] view plain copy
原创粉丝点击