Use Java to generate 100 numbers not repeated between 1 and
Import java. util. arrays;/*** use Java to generate 100 numbers 1-150 */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 and then output Arrays. sort (resultArr); for (Integer num: resultArr) {System. out. println (num );}} /*** generate a random number * @ param minNum minimum number * @ param maxNum maximum number * @ param numCount Number * @ return result array */public static int [] produceNum (int minNum, int maxNum, int numCount) {// input parameter verification // if the number of random numbers is greater than the range where the random number is generated; or if the maximum number is less than the minimum number, // return null directly, the input parameter does not meet the requirements. if (numCount> (maxNum-minNum + 1) | maxNum <minNum) {return null ;} // array where the result is stored int [] resultArr = new int [numCount]; // count records the number of generated random numbers int count = 0; while (count <numCount) {// generate a random number int num = (int) (Math. random () * (maxNum-minNum) + minNum; // flag determines whether the generated random number has been in the array boolean flag = true; // traverse the random numbers generated in the array for (int I = 0; I
Code explanation
1 int num = (int) (Math. random () * (maxNum-minNum) + minNum;
Math. random () produces 0 ~ Random Number of the double type between 1
Math. random () * 10 will get 0 ~ Random Number between 10. After int conversion, It is 0 ~ 9. If you give Math. random () * 10 + 1, it is 1 ~ Random Number between 11. If you want to convert int to 1 ~ 10.
Here 1 is equivalent to the minimum value in the program, and 11 is the maximum value.
In this way, a random number is generated.(Int) (Math. random () * (maxNum-minNum) + minNum
2For (int I = 0; I
Because the num generated each time is random, the repetition problem cannot be guaranteed. Therefore, only when the numbers in the generated array are compared and the numbers are the same will the data be re-generated, then, it is added to the array.