首页 > 编程语言 > 详细

java.lang.IllegalArgumentException: n must be positive

时间:2015-05-25 11:22:46      阅读:5269      评论:0      收藏:0      [点我收藏+]
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);
 




java.lang.IllegalArgumentException: n must be positive

原文:http://www.cnblogs.com/sagech/p/4527387.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!