将生成随机数的方法封装成通用方法类
时间: 2023-12-10 22:58:00 浏览: 13
以下是一个简单的通用方法类,可以生成指定范围内的随机数:
```java
import java.util.Random;
public class RandomNumberGenerator {
private static final Random rand = new Random();
public static int generateRandomInt(int min, int max) {
if (min > max) {
throw new IllegalArgumentException("min cannot be greater than max");
}
return rand.nextInt((max - min) + 1) + min;
}
public static double generateRandomDouble(double min, double max) {
if (min > max) {
throw new IllegalArgumentException("min cannot be greater than max");
}
return rand.nextDouble() * (max - min) + min;
}
}
```
使用示例:
```java
int randomInt = RandomNumberGenerator.generateRandomInt(1, 10);
double randomDouble = RandomNumberGenerator.generateRandomDouble(1.0, 10.0);
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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://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)