因为想当然的认为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));
应用:
生成乱序不重复数组
- package com.cn.wuliu.utils;
- import java.util.Random;
-
-
- public class Arith {
-
- public static int[] getSequence(int maxnum) {
- int[] sequence = new int[maxnum];
- for(int i = 0; i < maxnum; i++){
- sequence[i] = i;
- }
-
-
- 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;
- }
-
-
- 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;
- }
-
- 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]);
- }
- }
- }