Java生成范围随机数

Java生成500到1500的随机数

package number;

import java.util.Random;

public class RandomTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int i=0;i<100;i++){
			System.out.println(getRandom());
		}
		
		
	}
	public static int getRandom(){
		int max=1500;
		int min=500;
		Random random = new Random();
		int s = random.nextInt(max)%(max-min+1) + min;
		return s;
	}
}
 
### 如何在 Java生成指定范围内的随机数Java生成指定范围内的随机整数可以通过多种方式实现。以下是几种常见的方法及其对应的代码示例。 #### 方法一:使用 `Math.random()` 函数 `Math.random()` 是一种内置的方法,用于生成介于 `[0, 1)` 范围内的伪随机浮点数。通过简单的算术运算可以将其映射到所需的范围内[^1]。 ```java public class RandomNumberGenerator { public static int getRandomNumberInRange(int min, int max) { if (min >= max) { throw new IllegalArgumentException("Max must be greater than min"); } return (int)(Math.random() * ((max - min) + 1)) + min; } public static void main(String[] args) { System.out.println(getRandomNumberInRange(10, 20)); } } ``` 此方法利用 `(max - min) + 1` 来确保最大值被包含在内,并通过加法操作调整最小值起点[^1]。 --- #### 方法二:使用 `ThreadLocalRandom` 类 `ThreadLocalRandom` 提供了一种线程安全的方式来生成随机数,适合多线程环境下的应用。它可以直接生成指定范围内的随机整数[^2]。 ```java import java.util.concurrent.ThreadLocalRandom; public class ThreadLocalRandomExample { public static int getRandomNumberInRange(int min, int max) { return ThreadLocalRandom.current().nextInt(min, max + 1); } public static void main(String[] args) { System.out.println(getRandomNumberInRange(10, 20)); } } ``` 这里需要注意的是,`nextInt(min, max + 1)` 的第二个参数是排除性的上限,因此需要加上 `1` 才能包含期望的最大值[^2]。 --- #### 方法三:使用 Apache Commons Lang 库 Apache Commons Lang 提供了一个便捷的工具类 `RandomUtils`,其中包含了生成随机数的功能[^3]。 ```java import org.apache.commons.lang3.RandomUtils; public class ApacheCommonsLangExample { public static int getRandomNumberInRange(int startInclusive, int endExclusive) { return RandomUtils.nextInt(startInclusive, endExclusive); } public static void main(String[] args) { System.out.println(getRandomNumberInRange(10, 21)); // 注意这里是开区间 } } ``` 该库中的 `RandomUtils.nextInt(startInclusive, endExclusive)` 方法允许定义起始值(含)和结束值(不含),从而简化了边界处理逻辑[^3]。 --- #### 总结 以上三种方法各有优劣: - 如果追求简单性和兼容性,可以选择基于 `Math.random()` 的解决方案。 - 对于高性能需求或者多线程场景下推荐使用 `ThreadLocalRandom`。 - 若项目已经引入了第三方依赖,则可考虑采用功能强大的 Apache Commons 工具集来减少自定义编码量。 无论选用哪种方案,请务必注意输入验证以及上下限设置的一致性问题以避免潜在错误发生。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值