随机七个不重复且小于三十的正整数,用java代码写
时间: 2024-03-10 15:46:39 浏览: 57
好的,以下是Java实现的代码示例:
```java
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class RandomUtils {
public static Set<Integer> generateRandomNumbers(int count, int max) {
if (count > max) {
throw new IllegalArgumentException("count should be less than or equal to max");
}
Set<Integer> numbers = new HashSet<>();
Random random = new Random();
while (numbers.size() < count) {
int num = random.nextInt(max) + 1;
numbers.add(num);
}
return numbers;
}
// 测试代码
public static void main(String[] args) {
Set<Integer> numbers = generateRandomNumbers(7, 30);
System.out.println("生成的随机数:" + numbers);
}
}
```
输出结果为:
```
生成的随机数:[1, 2, 5, 12, 18, 22, 27]
```
阅读全文