java 生成五位随机数
时间: 2023-11-17 22:06:23 浏览: 106
java生成随机数
5星 · 资源好评率100%
生成五位不重复的随机数的方法有多种,下面是两个示例代码:
示例1:
```java
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class RandomNumber {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
Random random = new Random();
while (set.size() < 5) {
int number = random.nextInt(100);
set.add(number);
}
for (int num : set) {
System.out.println(num);
}
}
}
```
示例2:
```java
import java.util.Arrays;
import java.util.Random;
public class RandomNumber {
public static void main(String[] args) {
int[] numbers = new int[5];
Random random = new Random();
for (int i = 0; i < numbers.length; i++) {
int number = random.nextInt(100);
for (int j = 0; j < i; j++) {
if (number == numbers[j]) {
number = random.nextInt(100);
j = -1;
}
}
numbers[i] = number;
}
Arrays.stream(numbers).forEach(System.out::println);
}
}
```
阅读全文