用java写一个从1-33个数字里面随机选出7个不能重复的数字且从小到大排列,和从16个数字里面选出4个不能重复的数字且从小到大排列
时间: 2023-05-28 18:04:02 浏览: 99
import java.util.Arrays;
import java.util.Random;
public class RandomNumber {
public static void main(String[] args) {
// 从1-33个数字里面随机选出7个不能重复的数字且从小到大排列
int[] nums1 = new int[7];
Random random = new Random();
for (int i = 0; i < 7; i++) {
int num = random.nextInt(33) + 1;
while (contains(nums1, num)) {
num = random.nextInt(33) + 1;
}
nums1[i] = num;
}
Arrays.sort(nums1);
System.out.println(Arrays.toString(nums1));
// 从16个数字里面选出4个不能重复的数字且从小到大排列
int[] nums2 = new int[4];
int[] allNums = new int[16];
for (int i = 0; i < 16; i++) {
allNums[i] = i + 1;
}
for (int i = 0; i < 4; i++) {
int index = random.nextInt(16 - i);
nums2[i] = allNums[index];
allNums[index] = allNums[15 - i];
}
Arrays.sort(nums2);
System.out.println(Arrays.toString(nums2));
}
private static boolean contains(int[] nums, int num) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == num) {
return true;
}
}
return false;
}
}
阅读全文