package com.wzs; import java.util.Arrays; import java.util.Random; /** * 获取指定范围内的不重复随机数 * * @author wWX154783 * */ public class Test { public static void main(String[] args) { int[] arrIntger = rang(2, 50, 48); Arrays.sort(arrIntger);// 排序 System.out.println(Arrays.toString(arrIntger)); } static int[] rang(int startNumber, int endNumber, int count) { int total = 0;// 已经生成数据量 boolean flag = false;// 是否重复,true 重复,false 不重复 int[] intArray = new int[count]; Random random = new Random(); int intTemp;// 随机生成的临时数据 if (count > (endNumber - startNumber)) { System.out.print("生成数据总量不能大于 " + (endNumber - startNumber) + " !"); System.exit(0); } while (total < count) { intTemp = random.nextInt(endNumber - startNumber + 1) + startNumber; // 判断是否与生成的数据相等 for (int j = 0; j < total; j++) { if (intTemp == intArray[j]) { flag = true; break; } else { flag = false; } } if (false == flag) { intArray[total] = intTemp; total++; } } return intArray; } }
输出结果:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]