java.lang.IllegalArgumentException: n must be positive

public static String  randomKey(){
		Random random = new Random();
		int key = random.nextInt(((int)System.currentTimeMillis()));
		return String.valueOf(key);
	}

  直接调用方法,发生异常:

Exception in thread "main" java.lang.IllegalArgumentException: n must be positive
    at java.util.Random.nextInt(Random.java:300)
    at com.stresstest.example.RandomTest.randomKey(RandomTest.java:24)
    at com.stresstest.example.RandomTest.main(RandomTest.java:15)

异常说明:

java.lang.IllegalArgumentException: n must be positive
参数异常,n必须是一个整数,显然(int)System.currentTimeMillis()产生的值不是一个正数。

分析:
  系统产生的异常,测试时系统正常,上线之后某一天之后产生了异常。
查看System.currentTimeMillis()产生了问题,产生异常时间是2015-05-23当天开始往后,一直报错。之前就没事

时间:2015-05-23
测试结果:正常
System.currentTimeMillis():1432350368523
(int)System.currentTimeMillis():2126349176
randomKey():1369912950
时间:2015-05-24
测试结果:
1432436706512
-2082194224 Exception in thread "main" java.lang.IllegalArgumentException: n must be positive at java.util.Random.nextInt(Random.java:300) at com.stresstest.example.RandomTest.randomKey(RandomTest.java:24) at com.stresstest.example.RandomTest.main(RandomTest.java:15)

  因此可以知道结果,阴性问题,值得注意,至于long型转换为int型出现问题在这里不做深究,有这个问题深层研究的请补充。

解决办法:

int key = random.nextInt(((int)System.currentTimeMillis()));
修改为:
  1.random.nextInt(((int)System.currentTimeMillis()/1000));
  2.random.nextInt(999999999);
 




转载于:https://www.cnblogs.com/sagech/p/4527387.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值