import java.util.Random; public class Rand { public static void main(String[] args) { final int[] nums = new int[m]; Random rand = new Random(); for(int i = 0; i < nums.length; i++){ int randNum = rand.nextInt(m);//simple test, the number not grater than m boolean isExistingNum = false; //check whether it's already in the array; for(int j =0; j < i; j++){ if(nums[j] == randNum){ isExistingNum = true; break; } } if(isExistingNum){ i--; }else{ nums[i] = randNum; } } //print the array for(int i = 0; i < nums.length; i++){ System.out.println(nums[i]); } } }
生成n以内的m个随机数
最新推荐文章于 2022-07-08 12:45:00 发布