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);
 




posted @ 2015-05-25 11:12  浪荡小新  阅读(11575)  评论(0编辑  收藏  举报