# Java is used to generate 100 non repeating Numbers between 1 150

• 2020-06-12 09:02:35
• OfStack

The core code

``````
import java.util.Arrays;

/**
*  with Java produce 100 a 1-150 The number of
*/
public class RandomTest {

public static void main(String[] args) {
int[] resultArr = produceNum(1, 150, 100);
for (Integer num : resultArr) {
System.out.println(num);
}

System.out.println("+++++++++++++++++===================+++++++++++++");

//  Sort the result array before printing it out
Arrays.sort(resultArr);
for (Integer num : resultArr) {
System.out.println(num);
}
}

/**
*  Generate random Numbers
* @param minNum  The minimum number
* @param maxNum  The largest number
* @param numCount  The number of Numbers produced
* @return  The result array
*/
public static int[] produceNum(int minNum, int maxNum, int numCount) {

//  Into the reference check
//  If the number of random Numbers is greater than the range of random number generation; Or the maximum number is less than the minimum number
//  Direct return null , indicating that the participation does not meet the requirements
if (numCount > (maxNum - minNum + 1) || maxNum < minNum) {
return null;
}

//  An array of results
int[] resultArr = new int[numCount];

// count  Record the number of random Numbers generated
int count = 0;

while(count < numCount) {

//  Random number generation
int num = (int) (Math.random() * (maxNum - minNum)) + minNum;

// flag  Defines whether the random number generated this time is already in the array
boolean flag = true;

//  The random number generated in the traversal group
for (int i=0; i<count; i++) {

//  Compared to the random number generated this time
if (num == resultArr[i]) {

//  If the same value already exists, jump out for Loop, continue to the outer layer while Loop, produce down 1 A random number
flag = false;
break;
}
}

//  If the random number generated does not exist in the array, the random number is stored in the array
if (flag) {
resultArr[count] = num;

//  The number of random Numbers generated in the array plus 1
count++;
}
}

return resultArr;
}
}
``````