java中产生10个120到250之间不重复的随机数
时间: 2024-03-09 21:47:53 浏览: 85
可以使用Java中的Random类和HashSet集合来实现产生10个120到250之间不重复的随机数。具体实现代码如下:
```java
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
public class RandomNumberGenerator {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
Random rand = new Random();
while (set.size() < 10) {
int num = rand.nextInt(131) + 120;
set.add(num);
}
System.out.println("10 random numbers between 120 and 250:");
for (int num : set) {
System.out.println(num);
}
}
}
```
运行该代码,会输出10个120到250之间不重复的随机数。
相关问题
Java代码实现两个小数之间十个不重复随机数
可以使用Java的Random类来生成随机数,然后使用HashSet来存储已生成的随机数,以保证不重复。下面是示例代码:
```java
import java.util.HashSet;
import java.util.Random;
import java.math.BigDecimal;
public class RandomDecimal {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("2.5"); // 第一个小数
BigDecimal num2 = new BigDecimal("7.3"); // 第二个小数
// 将两个小数转换成整数,放大10的16次方倍
BigDecimal max = num1.max(num2).multiply(new BigDecimal("10000000000000000"));
BigDecimal min = num1.min(num2).multiply(new BigDecimal("10000000000000000"));
HashSet<BigDecimal> set = new HashSet<>();
Random random = new Random();
while (set.size() < 10) {
BigDecimal randomNum = new BigDecimal(random.nextDouble()).multiply(max.subtract(min)).add(min);
set.add(randomNum);
}
for (BigDecimal num : set) {
System.out.println(num.divide(new BigDecimal("10000000000000000"))); // 将随机数还原成小数输出
}
}
}
```
这段代码会生成10个在2.5和7.3之间的不重复的随机小数。
java生成10个1到20之间不重复的随机数
好的,以下是Java代码实现:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Set<Integer> set = new HashSet<>();
Random random = new Random();
while (set.size() < 10) {
int num = random.nextInt(20) + 1;
set.add(num);
}
System.out.print("生成的随机数:");
for (int num : set) {
System.out.print(num + " ");
}
}
}
```
程序的主要思路是使用Set来存储不重复的随机数,使用Java自带的Random类来生成随机数,每次生成的随机数在1到20之间,然后将随机数添加到Set中,直到Set中的元素个数达到10个为止,最后输出Set中的所有元素即可。
阅读全文
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)